segmentation error while using container.erase(iterator)

  c++, containers, erase

I have this program that will erase the odd number from the vector container, but I don’t know
why I get segmentation error.
I tried to change the condition of if to (cc % 2 == 0) and this will work and erase even numbers instead but why when this is (c % 2 != 0) it will not work to delete the odd numbers!

here is my code :

int main()
{
    std::vector<int> ivec = {0,1,1,2,3,5,8,13,21,34,55,89};
    for(auto j:ivec)
    {
        int cc = j;
        std::vector<int>::iterator mustdelete = find(ivec.begin(),ivec.end(),cc); 
        if (cc % 2 != 0)
            ivec.erase(mustdelete);//delete the numbers that are odd.
    }
return 0;
}

Source: Windows Questions C++

LEAVE A COMMENT