c++ - Problem with invalidation of STL iterators when calling erase -


the stl standard defines when erase occurs on containers such std::deque, std::list etc iterators invalidated.

my question follows, assuming list of integers contained in std::deque, , pair of indicies indicating range of elements in std::deque, correct way delete elements?

so far have following, problem here assumed end invalidated after erase:

#include <cstddef> #include <deque>  int main() {    std::deque<int> deq;    (int = 0; < 100; deq.push_back(i++));     // range, 11th 51st element    std::pair<std::size_t,std::size_t> r(10,50);     std::deque<int>::iterator = deq.begin() + r.first;    std::deque<int>::iterator end = deq.begin() + r.second;     while (it != end)    {       if (*it % 2 == 0)       {          = deq.erase(it);       }       else         ++it;    }     return 0; } 

examining how std::remove_if implemented, seems there costly copy/shift down process going on.

  • is there more efficient way of achieving above without copy/shifts

  • in general deleting/erasing element more expensive swapping next nth value in sequence (where n number of elements deleted/removed far)

note: answers should assume sequence size quite large, +1mil elements , on average 1/3 of elements erasure.

i'd use erase-remove idiom. think wikipedia article linked shows you're doing -- removing odd elements.

the copying remove_if no more costly happens when delete elements middle of container. might more efficient.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -