1

I was wondering how can I erase an element of a vector while keeping the iterator?Here I am looping through vector of vectors of type int :

vector< vector<int> >::iterator row;
vector<int>::iterator col;
for (row = vvi.begin(); row != vvi.end(); row++) {
    for (col = row->begin(); col != row->end(); col++) {
        if(*col==55)
        {
           //  col=row.erase(col); ?
        }

    }
}
nakiya
  • 14,063
  • 21
  • 79
  • 118
  • 2
    Possible duplicate of [Erasing from a std::vector while doing a for each?](https://stackoverflow.com/questions/3938838/erasing-from-a-stdvector-while-doing-a-for-each) – nakiya May 24 '17 at 05:06

1 Answers1

0

In your code, if there are multiple elements equal to 55, there would be multiple times of erase vector elements which will take much overhead to move elements. A better solution is to follow erase-remove idiom to move all the qualified elements to the end of the vector, then erase them together in one time. For example:

vector< vector<int> >::iterator row;
vector<int>::iterator col;
for (row = vvi.begin(); row != vvi.end(); row++) {
     row->erase( std::remove( row->begin(), row->end(), 55), row->end());
}

std::remove will move all the element which equal to 55 to the end of the vector and return the iterator of the head of them. row->erase(iterator1, iterator2) will erase all the elements between 2 iterators.

And you don't need to care iterator anymore.

cartman
  • 732
  • 2
  • 8
  • 20
  • 1
    Hm , it says that remove is not in std? – Ivan Ivanov May 24 '17 at 05:35
  • try #include – cartman May 24 '17 at 05:37
  • 1
    Yes it worked out,I am testing it out not on ints, but on class Human for example and the class has property age ,I tried to replace 55 with row->age,however it is not recognized ,any ideas why? – Ivan Ivanov May 24 '17 at 05:38
  • In that case, you can try std::remove_if and customize the condition to remove element. like the example in https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom – cartman May 24 '17 at 05:43
  • If you think the answer is useful, please vote for me :) – cartman May 24 '17 at 05:44
  • Yeah sure,can you lastly show what function should I create and pass to the erase methond in order to delete for example humans with age==20? – Ivan Ivanov May 24 '17 at 05:49
  • Stranegly I declared it in the class and instead of 55 I replaced it with isAge20,but the compiler says : 'isAge20' is not declared in the scope ,here is how it looks : row->erase( std::remove_if( row->begin(), row->end(), isAge20), row->end()); – Ivan Ivanov May 24 '17 at 06:47