0

I have codes like this:

    vector<int> v = {1,-2,-2,3};
    int gsum = 0; //global sum
    for(auto i=v.begin(); i!=v.end(); ){
        if(*i >= 0){
            gsum += *i;
            v.erase(i,i+1);
        }else{
            v.insert(i, gsum);
            gsum = 0;
            i+=2;
        }
    }for (auto i : v) {
        cout<<i<<ends;
    }

Run it, and find that sometimes it never ends, sometimes it prints extremely large or small numbers, sometimes it throws "heap-buffer-overflow". Can anyone explain it?

1 Answers1

0

The line v.erase(i,i+1) invalidates all iterators into v - including the ones your for loop is using to iterate the container. So, after that line your loop is using invalid iterators and your code has undefined behaviour.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70