deleting from a vector
-
I wrote some C++ code to create a vector and then try to delete all occurrences of 3 in it:
vector myVector = { 1, 2, 3, 4, 5, 3, 2 };
for (auto i = myVector.begin(); i != myVector.end(); i++) { if (\*i == 3) myVector.erase(i); }
However, it doesn't work right. It gives this error: Expression: can't increment invalidated vector iterator I guess you can't increment the iterator after you erase the element. Anyone know how to fix this? Thanks.
-
I wrote some C++ code to create a vector and then try to delete all occurrences of 3 in it:
vector myVector = { 1, 2, 3, 4, 5, 3, 2 };
for (auto i = myVector.begin(); i != myVector.end(); i++) { if (\*i == 3) myVector.erase(i); }
However, it doesn't work right. It gives this error: Expression: can't increment invalidated vector iterator I guess you can't increment the iterator after you erase the element. Anyone know how to fix this? Thanks.
The problem comes because as soon as you remove an element then all the rest effectively move nearer the beginning, and thus their positions are out of sync with the iterator. You could try a reverse iterator as detailed at std::vector - cppreference.com[^].
-
I wrote some C++ code to create a vector and then try to delete all occurrences of 3 in it:
vector myVector = { 1, 2, 3, 4, 5, 3, 2 };
for (auto i = myVector.begin(); i != myVector.end(); i++) { if (\*i == 3) myVector.erase(i); }
However, it doesn't work right. It gives this error: Expression: can't increment invalidated vector iterator I guess you can't increment the iterator after you erase the element. Anyone know how to fix this? Thanks.
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