How to Replace an Element in a Vector in C++? Last Updated : 23 Jul, 2025 Comments Improve Suggest changes Like Article Like Report In this article, we will learn how to replace an element in a vector in C++.The most efficient method to replace the old value with a new value is by using replace() method. Let’s take a look at an example: C++ #include <bits/stdc++.h> using namespace std; int main() { vector<int> v = {1, 3, 6, 2, 7, 2}; // Replace all 2s with 22 replace(v.begin(), v.end(), 2, 22); for (auto i : v) cout << i << " "; return 0; } Output1 3 6 22 7 22 Explanation: The replace() method replace all the occurrences of the given element in the vector with the new value.There are also some other method in C++ by which we can replace the given old values with new value. Some of them are as follows:Using transform()The transform() method allows us to apply a transformation (e.g., replacing elements) to all elements in the vector based on a transformation function. C++ #include <bits/stdc++.h> using namespace std; int main() { vector<int> v = {1, 3, 6, 2, 7, 2}; // Replacing all 2s in vector with 22 transform(v.begin(), v.end(), v.begin(), [](int i) { return i == 2 ? 22 : i; }); for (auto i : v) cout << i << " "; return 0; } Output1 3 6 22 7 22 Manually Using LoopIn this method, iterate through the vector using a loop and check the element at every index. If it is equal to given value, then assign it the new value. C++ #include <bits/stdc++.h> using namespace std; int main() { vector<int> v = {1, 3, 6, 2, 7, 2}; // Replacing all 2s in vector with 22 for (auto &i : v) { if (i == 2) i = 22; } for (auto i : v) cout << i << " "; return 0; } Output1 3 6 22 7 22 Create Quiz Comment T the_star_emperor Follow 0 Improve T the_star_emperor Follow 0 Improve Article Tags : C++ Programs C++ STL cpp-vector CPP Examples +1 More Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read Like