As you guessed, erase invalidates all iterators on the container. Your problem is known as the Erase–remove idiom[^] There are different ways of solving it: 1. The "manual" way:
auto pos = myVector.begin();
size_t i=0;
while (pos != myVector.end())
{
if (*pos ==3)
{
myVector.erase(pos);
pos = myVector.begin() + i;
}
else
{
++i;
++pos;
}
}
2. The "semi-automatic" way:
auto pos = myVector.begin();
while (pos != myVector.end())
{
if (*pos ==3)
pos = myVector.erase(pos); //erase returns an iterator pointing to next element
else
++pos;
}
3. The "old fully automatic way":
myVector.erase(std::remove(myVector.begin(),
myVector.end(), 3),
myVector.end());
4. The "new fully automatic way" (since C++20):
std::erase (myVector, 3);
Disclaimer: I didn't compile any of the code above; some errors may/will exist :)
Mircea