How to Replace All Occurrences of an Element in a Vector in C++?
Last Updated :
13 Feb, 2024
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++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector
= { 20, 30, 10, 50, 20, 30, 10, 50 };
int oldVal = 10;
int newVal = 100;
cout << "Original Vector: " ;
for ( int element : myVector) {
cout << element << " " ;
}
cout << endl;
replace(myVector.begin(), myVector.end(), oldVal,
newVal);
cout << "Updated Vector: " ;
for ( int element : myVector) {
cout << element << " " ;
}
cout << endl;
return 0;
}
|
Output
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)
Share your thoughts in the comments
Please Login to comment...