Replacing elements in vector using erase and insert

23,000

Solution 1

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);

Solution 2

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");

Solution 3

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.

Share:
23,000

Related videos on Youtube

Nikolai Stiksrud
Author by

Nikolai Stiksrud

Updated on July 09, 2022

Comments

  • Nikolai Stiksrud
    Nikolai Stiksrud almost 2 years
    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?

    • Shimon Rachlenko
      Shimon Rachlenko about 11 years
      Shouldn't you pass the vector as a reference?
    • Pete Becker
      Pete Becker about 11 years
      You don't need to erase and insert. Just assign: *it = replacement;. That eliminates any issues about iterator invalidation, and removes a bunch of churning to remove an element then open up a hole for insertion where that element used to be.
  • Enn Michael
    Enn Michael over 7 years
    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.
  • Toby Speight
    Toby Speight almost 7 years
    @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.

Related