std::vector iterator invalidation

前端 未结 2 874
迷失自我
迷失自我 2020-11-29 08:31

There have been a few questions regarding this issue before; my understanding is that calling std::vector::erase will only invalidate iterators which are at a p

相关标签:
2条回答
  • 2020-11-29 09:05

    after erasing an element, is the iterator at that position still valid

    No; all of the iterators at or after the iterator(s) passed to erase are invalidated.

    However, erase returns a new iterator that points to the element immediately after the element(s) that were erased (or to the end if there is no such element). You can use this iterator to resume iteration.


    Note that this particular method of removing odd elements is quite inefficient: each time you remove an element, all of the elements after it have to be moved one position to the left in the vector (this is O(n2)). You can accomplish this task much more efficiently using the erase-remove idiom (O(n)). You can create an is_odd predicate:

    bool is_odd(int x) { return (x % 2) == 1; }
    

    Then this can be passed to remove_if:

    vec.erase(std::remove_if(vec.begin(), vec.end(), is_odd), vec.end());
    
    0 讨论(0)
  • 2020-11-29 09:18

    Or:

    class CIsOdd
    {
    public:
        bool operator()(const int& x) { return (x % 2) == 1; }
    };
    
    vec.erase(std::remove_if(vec.begin(), vec.end(), CIsOdd()), vec.end());
    
    0 讨论(0)
提交回复
热议问题