Calling erase () on an iterator but not deleting the correct item

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;
}

. .

+4
2

it++ for, for; , . .

for (list<int>::iterator it = numbers.begin(); it != numbers.end(); )

LIVE

+5

, / . , .

list<int>::iterator it = numbers.begin();
while (it != numbers.end()) {
{
list<int>::iterator next_it = it;
++next_it;

// Do your insertion or deletion here

it = next_it;
}
0

Source: https://habr.com/ru/post/1693340/


All Articles