Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 576
Nikolai Stiksrud Avatar asked Apr 14 '13 11:04

Nikolai Stiksrud


People also ask

How do you replace an element in a vector?

To replace an element in Java Vector, set() method of java. util. Vector class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element.

How do you remove a specific element from a vector?

The erase() function can remove an element from the beginning, within, or end of the vector. In order to remove all the elements from the vector, using erase(), the erase() function has to be repeated the number of times there are elements, beginning from the first element.

How do you replace a number in a vector?

To replace a value in an R vector, we can use replace function. It is better to save the replacement with a new object, even if you name that new object same as the original, otherwise the replacements will not work with further analysis.


1 Answers

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);
like image 189
alexrider Avatar answered Nov 15 '22 17:11

alexrider