In C++, Vectors are similar to arrays but unlike the arrays, they can change their size dynamically when the elements are inserted or deleted. We might encounter use cases where we will have to replace all of the occurrences of a specific element in a vector. In this article, we will explore how to replace all the occurrences of a specific element in C++.
Example:
Input: myVector = {20,30,10,50, 10} Output: myVector = {20, 30, 100 ,50, 100} // replaced all occurrence of 10 with 100
Replace All Occurrences of an Element in a Vector in C++
The Standard Template Library (STL) of C++ provides a std::replace() function which can be used to replace all the occurrences of a specific element in the given range. We have to pass the beginning and ending iterators of the vector to the replace() function along with the element we want to replace and the new element.
Syntax of std::replace()
replace(begin, end, oldValue, newValue)
C++ Program to Replace All Occurrences of an Element in Vector
// C++ program to illustrate how to replace all the // occurences of a specific element #include <algorithm> #include <iostream> #include <vector> using namespace std;
int main()
{ // intitialize a vector
vector< int > myVector
= { 20, 30, 10, 50, 20, 30, 10, 50 };
// Declare the value you want to replace
int oldVal = 10;
int newVal = 100;
// Print the original vector
cout << "Original Vector: " ;
for ( int element : myVector) {
cout << element << " " ;
}
cout << endl;
// Replace all occurrences of oldValue with newValue
replace(myVector.begin(), myVector.end(), oldVal,
newVal);
// Print the updated vector
cout << "Updated Vector: " ;
for ( int element : myVector) {
cout << element << " " ;
}
cout << endl;
return 0;
} |
Original Vector: 20 30 10 50 20 30 10 50 Updated Vector: 20 30 100 50 20 30 100 50
Time Complexity: O(N), where N is the total number of elements in the vector
Auxiliary Space: O(1)