Weird behaviour with vector::erase and std::remove_if with end range different from vector.end()

Posted by Edison Gustavo Muenz on Stack Overflow See other posts from Stack Overflow or by Edison Gustavo Muenz
Published on 2010-04-26T21:26:12Z Indexed on 2010/04/26 21:43 UTC
Read the original article Hit count: 297

Filed under:
|

Hi,

I need to remove elements from the middle of a std::vector.

So I tried:

struct IsEven {
    bool operator()(int ele)
    {
        return ele % 2 == 0;
    }
};

    int elements[] = {1, 2, 3, 4, 5, 6};
    std::vector<int> ints(elements, elements+6);

    std::vector<int>::iterator it = std::remove_if(ints.begin() + 2, ints.begin() + 4, IsEven());
    ints.erase(it, ints.end());

After this I would expect that the ints vector have: [1, 2, 3, 5, 6].

In the debugger of Visual studio 2008, after the std::remove_if line, the elements of ints are modified, I'm guessing I'm into some sort of undefined behaviour here.

So, how do I remove elements from a Range of a vector?

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl