The STL standard defines that when erasure occurs in containers such as std :: deque, std :: list etc, iterators are invalid.
My question is this, assuming a list of integers contained in std :: deque, and a pair of pointers indicating a range of elements in std :: deque, what is the correct way to remove all even elements?
So far, I have the following, however, the problem here is that the intended end is not valid after deletion:
#include <cstddef> #include <deque> int main() { std::deque<int> deq; for (int i = 0; i < 100; deq.push_back(i++)); // range, 11th to 51st element std::pair<std::size_t,std::size_t> r(10,50); std::deque<int>::iterator it = deq.begin() + r.first; std::deque<int>::iterator end = deq.begin() + r.second; while (it != end) { if (*it % 2 == 0) { it = deq.erase(it); } else ++it; } return 0; }
Studying how std :: remove_if is implemented, it seems like a very expensive copy / shift process is going on.
Is there a more efficient way to achieve the above without all copies / shifts
In general, deleting / deleting an element is more expensive than replacing it with the next nth value in the sequence (where n is the number of deleted / deleted elements)
Note: The answers suggest that the sequence size is quite large, + 1 mil elements and that on average 1/3 of the elements will be erased.
Matthieu N.
source share