0

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;
}
6
  • find is a function of header algorithm, Commented Sep 25, 2021 at 6:37
  • ivec.erase(std::remove_if(ivec.begin(), ivec.emd(), [](int n) { return n%2; }), ivec.end()); -- You want to delete something from a sequence container with a given condition, there is no need to write buggy, inefficient, hand-coded for loops. Commented Sep 25, 2021 at 6:46
  • 4
    You can't delete elements from a vector inside a range-based-for, because of iterator invalidation rules. However, the whole approach of iterating + finding the iterator is really inefficient. Use the erase-remove-idiom instead. Commented Sep 25, 2021 at 6:47
  • I suspect that it's because you're deleting items in the vector that you're looping over. It happens to work for even numbers because you have no even repeats but you have two 1's Commented Sep 25, 2021 at 6:51
  • 1
    See here en.cppreference.com/w/cpp/language/range-for . You are erasing within loop. The vector compacts and according to documentation iterator becomes invalid. In practice it starts pointing to the next element. The last element is odd, so you go out of bounds and segfault. Use std::remove_if Commented Sep 25, 2021 at 6:55

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.