Nikolai Stiksrud
Nikolai Stiksrud

Reputation: 155

Replacing elements in vector using erase and insert

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'd like this function to replace all occurrences of the string old in the vector with the string replacement. But when calling this function, it simply doesn't change the vector at all. I'm not sure if I am using the erase and insert functions properly. Any ideas?

Upvotes: 7

Views: 24992

Answers (3)

alexrider
alexrider

Reputation: 4463

At first you need to pass vector by reference, not by value.

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

Second erase and insert invalidates it, you need to update it with new iterator returned by erase

it = my_vector_2.erase(it);  
it = my_vector_2.insert(it,replacement);

Upvotes: 9

Kerrek SB
Kerrek SB

Reputation: 477010

There's an 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");

Upvotes: 5

bash.d
bash.d

Reputation: 13207

You are passing your std::vector as a value. In order to Change the std::vector you pass to the function, declare it as a reference

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

The & denotes that you pass your std::vector by reference and so you can access the object you passed.

And don't erase the element, simply replace it.

Upvotes: 2

Related Questions