The code is going fine, but when I execute, 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; } 

    1 answer 1

    After deleting an item, iterators become invalid. It would be correct to write as follows (I replaced the for while with while , since you declared it out of the loop, and the while in this case looks better. 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 delete only one element, you can write it as follows:

     auto it = std::find( v.begin(), v.end(), "+" ); if ( it != v.end() ) v.erase( it ); 
    • in the second example, all elements with a plus will be removed from the vector, and I need to sting only the first positive element that I encountered. For the first example, thank you very much. I understood what the error was - perfect
    • @perfect In your first example, all elements with a "+" are deleted, since you do not complete the cycle. - Vlad from Moscow
    • Yes indeed. thank you - perfect