Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What could be reason it crashes when I use vector::erase?

Tags:

c++

stl

vector

I am trying to do some operation on vector. And calling erase on vector only at some case.

here is my code

while(myQueue.size() != 1)
{
    vector<pair<int,int>>::iterator itr = myQueue.begin();
    while(itr != myQueue.end())
    {
        if(itr->first%2 != 0)
            myQueue.erase(itr);
        else
        {
            itr->second = itr->second/2;
            itr++;
        }
    }
}

I am getting crash in 2nd iteration.And I am getting this crash with message vector iterator incompatible .

What could be the reason of crash?

like image 439
Apoorva sahay Avatar asked Nov 21 '25 17:11

Apoorva sahay


1 Answers

If erase() is called the iterator is invalidated and that iterator is then accessed on the next iteration of the loop. std::vector::erase() returns the next iterator after the erased iterator:

itr = myQueue.erase(itr);
like image 172
hmjd Avatar answered Nov 23 '25 08:11

hmjd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!