Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Iterator problem, deleting a iterator (vector object) in a loop for (auto it = m

ID: 3839362 • Letter: I

Question

Iterator problem, deleting a iterator (vector object) in a loop

for (auto it = myVector.begin(); it != myVector.end(); ++it)
{
   it->value = it->value - 1; // i decrement all values by 1

   if (it->value == 0) // if a value reaches 0, i save the NAME of the value (vector object contains name,value).
   {
       outdatedValues.push_back(it->name); // after i save the name of the value, i want to erase the object from myVector.
       myVector.erase(it); // Here is the problem, if i delete the iterator, the loop is broken since i cant increment it.
   }
}

Explanation / Answer


myVector.erase(it) gives the next iterator, if you erase the end element it will point to .end()
At the end of the loop ++it is always called, so you increment .end() which was not allowed.

Simply checking for .end() gives an error, as you always skip an element on every iteration
(it gets 'incremented' by the return from .erase(), and then again by the loop)

You probably want something like to erase each element:

while (it != myVector.end()) {
        it = myVector.erase(it);  
}

When you want to erase elements based on condition, you can use like this.

for ( ; it != myVector.end(); ) {
if (condition) {
    it = myVector.erase(it);
} else {
    ++it;
}
}

So here is this I will recommend by the above explanation.

for (auto it = myVector.begin(); it != myVector.end(); ++it)
{
   it->value = it->value - 1;

   if (it->value == 0)
   {
       outdatedValues.push_back(it->name);
     
       while (it != myVector.end()) {
       myVector.erase(it);
}
      
   }
}


Hope this helps.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote