c++ – Runtime error when deleting a container item in a loop

Question:

The code builds fine, but when executed, I get an access error:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main(){
    vector<string> v;

    v.push_back("-");
    v.push_back("+");
    v.push_back("-");

    auto it = v.begin();

    for (it; it != v.end(); it++)
        if (*it == "+"){
            v.erase(it); // сдесь ошибка выполнения
        }

    return 0;
}

Answer:

After the element is removed, the iterators become invalid. It would be correct to write as follows (I replaced the for while with while , since you declared it iterator outside the loop, and the while looks better in this case. Although it is better to use a for loop with an iterator declaration inside the loop)

while ( it != v.end() )
    if (*it == "+"){
        it = v.erase(it);
    }
    else {
        ++it;
    }

The general approach for such a task is written in one line.

#include <algorithm>
#include <vector>
#include <string>

//...

v.erase( std::remove( v.begin(), v.end(), "+" ), v.end() );

If you want to remove only one element, then you can write as follows:

auto it = std::find( v.begin(), v.end(), "+" );

if ( it != v.end() ) v.erase( it );
Scroll to Top