How to Replace an Element in a Vector in C++?
Last Updated :
26 Feb, 2024
In C++, vectors are dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. In this article, we will see how to replace a particular element in a vector in C++.
Example:
Input:
myVector = {10,20,30,40,50,60}
Element to replace: 30
Replacement: 99
Output:
myVector = {10,20,99,40,50,60}
Replace a Particular Element in a Vector in C++
To replace a specific element in a std::vector in C++, we can use the std::replace() function provided by the STL. The std::replace() function replaces all occurrences of a specific value in a range with another value.
Approach
- The integer value to be replaced (to_replace) and the new value that will replace it (replace_with) are defined.
- A loop is used to iterate over the vector v. If an element in the vector is equal to to_replace, it is replaced with replace_with.
- The final state of the vector v (after replacement) is printed to the console.
C++ Program to Replace a Specific Element in a Vector
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > v = { 1, 2, 5, 3, 4, 8, 6, 8 };
int n = v.size();
int to_replace = 5;
int replace_with = 8;
cout << "The initial vector is: " ;
for ( int i = 0; i < n; i++) {
cout << v[i] << " " ;
}
cout << "\n" ;
cout << "Replacing " << to_replace << " with "
<< replace_with << endl;
for ( int i = 0; i < n; i++) {
if (v[i] == to_replace) {
v[i] = replace_with;
}
}
cout << "After Replacing vector is: " << endl;
for ( int i = 0; i < n; i++) {
cout << v[i] << " " ;
}
return 0;
}
|
Output
The initial vector is: 1 2 5 3 4 8 6 8
Replacing 5 with 8
After Replacing vector is:
1 2 8 3 4 8 6 8
Time complexity: O(N), N is size of vector.
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...