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;
}
meysamimani
  • 315
  • 2
  • 12
  • find is a function of header algorithm, – meysamimani Sep 25 '21 at 06: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. – PaulMcKenzie Sep 25 '21 at 06: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](https://en.wikipedia.org/wiki/Erase–remove_idiom) instead. – Lukas-T Sep 25 '21 at 06: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 – Ian4264 Sep 25 '21 at 06:51
  • 1
    See here https://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 – vpa1977 Sep 25 '21 at 06:55
  • It's not always work with event numbers, so it is actually undefined behavior. – The Long Nguyen Sep 25 '21 at 07:00

0 Answers0