Open In App

How to Replace an Element in a Vector in C++?

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  1. The integer value to be replaced (to_replace) and the new value that will replace it (replace_with) are defined.
  2. 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.
  3. 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++




// C++ Program to Replace a Specific Element in a Vector
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
// Driver Code
int main()
{
    // Create a vector and initialize it with some values
    vector<int> v = { 1, 2, 5, 3, 4, 8, 6, 8 };
  
    // Get the size of the vector
    int n = v.size();
  
    // Define the value to be replaced and the value to
    // replace it with
    int to_replace = 5;
    int replace_with = 8;
  
    // Print the initial vector
    cout << "The initial vector is: ";
    for (int i = 0; i < n; i++) {
        cout << v[i] << " ";
    }
    cout << "\n";
  
    // Perform replacement
    cout << "Replacing " << to_replace << " with "
         << replace_with << endl;
    for (int i = 0; i < n; i++) {
        if (v[i] == to_replace) {
            v[i] = replace_with;
        }
    }
  
    // Print the vector after replacement
    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)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads