Replacing elements in a vector by erasing and pasting

void replace(vector<string> my_vector_2, string old, string replacement){

    vector<string>::iterator it;
    for (it = my_vector_2.begin(); it != my_vector_2.end(); ++it){

        if (*it==old){
            my_vector_2.erase(it);
            my_vector_2.insert(it,replacement);

        }
    }

}

So, I would like this function to replace all occurrences of the string old in the vector with a replacement string. But when calling this function, it simply does not change the vector at all. I'm not sure if I use the erase and paste functions correctly. Any ideas?

+5
source share
3 answers

First you need to pass the vector by reference, not by value.

void replace(vector<string>& my_vector_2, string old, string replacement){

The second delete and insert will invalidate it, you need to update it with the new iterator returned by erasing

it = my_vector_2.erase(it);  
it = my_vector_2.insert(it,replacement);
+7
source

There is a ready-made algorithm for your problem:

#include <algorithm>
#include <string>
#include <vector>

std::vector<std::string> v;  // populate

std::replace(v.begin(), v.end(), "old", "new");
+3
source

You pass your std::vectoras a value. To change std::vector, you go to the function, declare it as a link

void replace(vector<string>& my_vector_2, string old, string replacement){ }

&means that you pass your std::vectorby reference and you can access the object you passed.

And do not erase the item, just replace it.

+2
source

All Articles