I try to remove elements in deque iterating a while loop. However seems that after erasing one element,the loop skip the next element . The code is the following
Example program
#include <iostream>
#include <string>
#include <deque>
#include <algorithm>
using namespace std;
deque<int*> queue;
int main()
{
int * a1 = new int(0);
int * a2 = new int(2);
int * a3 = new int(3);
int * a4 = new int(4);
int * a5 = new int(5);
queue.push_back(a1);
queue.push_back(a2);
queue.push_back(a3);
queue.push_back(a4);
queue.push_back(a5);
deque<int * >::iterator it = queue.begin();
while(it != queue.end())
{
std::cout << "Element :" << **it << std::endl;
//remove all elements are divided by 2
if((**it&1) == 0)
{
deque<int * >::iterator cur = (it+1);
std::cout << "Erase " << **it << std::endl;
queue.erase(std::remove(queue.begin(), queue.end(), *it), queue.end());
delete *it;
it = cur;
}
else
{
++it;
}
}
std::cout << "End" << std::endl;
}
The output is the following
*Element :0 Erase 0
Element :3
Element :4 Erase 4
End*
Seems that the the element 2 and 5 were skipped.
You have undefined behaviour, because you are dereferencing an invalid iterator at delete *it;
. To fix your immediate problem, you need something like
int * to_del = *it;
it = queue.erase(it);
delete to_del;
However, you should also avoid using int *
where int
is sufficient, and writing loops when there is something applicable in <algorithm>
bool is_even(int i) { return (i % 2) == 0; }
std::deque<int> queue { 0, 2, 3, 4, 5 };
queue.erase(std::remove_if(queue.begin(), queue.end(), is_even), queue.end());