I learn C ++ and I work on double linked lists, but I noticed something very peculiar when I tried to remove items from my list.
Problem . I insert an element before the value 2 in my list, numbers, and then try to remove any element that has a value of 1.
Expected : after I call erase () in my conditional expression in my first loop, my list, numbers, should be adjusted. The only values ββthat must contain numbers must contain 0.1234,2,3.
Respected . My numbers on the list contain the values ββ0,1,1234,2,3. As if nothing had been erased.
Code example :
#include "stdafx.h"
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> numbers;
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
numbers.push_front(0);
list<int>::iterator it = numbers.begin();
it++;
numbers.insert(it, 100);
cout << "Element: " << *it << endl;
list<int>::iterator eraseIt = numbers.begin();
eraseIt++;
eraseIt = numbers.erase(eraseIt);
cout << "Element: " << *eraseIt << endl;
for (list<int>::iterator it = numbers.begin(); it != numbers.end(); it++)
{
if (*it == 2)
{
numbers.insert(it, 1234);
}
if (*it == 1)
{
it = numbers.erase(it);
}
else
{
it++;
}
}
for (list<int>::iterator it = numbers.begin(); it != numbers.end(); it++)
{
cout << *it << endl;
}
return 0;
}
. .