7
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?

bash.d
  • 13,029
  • 3
  • 29
  • 42
Nikolai Stiksrud
  • 157
  • 2
  • 4
  • 7

3 Answers3

9

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);
Community
  • 1
  • 1
alexrider
  • 4,449
  • 1
  • 17
  • 27
  • Isn't this UB? Mentioning `it` after the call to `erase` is UB, and you do mention `it` in your call to `insert`. I think you have to use a workaround with `std::distance`. – Enn Michael Nov 05 '16 at 22:09
  • @Enn - did you not notice that `it` is assigned with the *result* of `erase()`? The invalidated iterator cannot be used, because `it` now holds a valid iterator; the same is true for the following `insert()` line. – Toby Speight May 02 '17 at 10:10
5

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");
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • It may or may not be worth noting that this deduces `T` in `replace` as `char[4]`. Operations that mix `string` and `const char*` should be efficient, so I don't think it matters in this case, but if you want to pass in string literals with different lengths then you need a conversion. – Steve Jessop Apr 14 '13 at 12:56
2

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.

bash.d
  • 13,029
  • 3
  • 29
  • 42