Search code examples
c++classvectormemory-managementerase-remove-idiom

call a function, inside a for loop, to remove elements in a vector (or list)


vector<node>::iterator it;
for(it;it!=vector_of_node.end();it++){
    if(it->get_name()=="MARIA"){
        vector_of_node.erase(it);
}

i hope the goal of my code is clear. i want to eliminate multiple objects (which are described in a class called node) from a vector (vector_of_nodes in this case). when i run my code i don't get any error from the compliler but i got a fail while it's running. i'm sure that the error is on this portion of code that i've shared. can you hel me?


Solution

  • Erasing while iterating is possible if you increment the iterator inside the loop depending on if you erase the element or not. If you erase it, the erase method returns the next iterator in the vector, if not, increment it yourself. Moreover, you need to initialize the iterator to begin.

    vector<node>::iterator it;
    for(it=vector_of_node.begin();it!=vector_of_node.end();){
        if(it->get_name()=="MARIA")
            it = vector_of_node.erase(it);
        else
            ++it;
    }