-1

I have a list like

2 , 6 , 6 , 8 , 9

I want this like

2, 8 , 9

I wrote a code

for(std::list<int>::iterator i = almostPrimeList.begin(); i != almostPrimeList.end(); ++i) {
  for(std::list<int>::iterator j = ++std::list<int>::iterator(i); j != almostPrimeList.end(); ++j) {
        if(*i == *j) {
            cout <<*i << " found";
            //almostPrimeList.remove(*i);
            break;
        }
  }
}

it appears found the values which has duplicate, but when I want to remove it make an infinite loop

theshemul
  • 388
  • 1
  • 6
  • 15

1 Answers1

0

If you erase the element pointed by i or j then the iterator becomes invalid.

Try:

++j ; // move to next
almostPrimeList.erase(i, j) ; // element pointedby j won't be rased
i = j ; // ok, reinitialize i
break ;
marom
  • 5,064
  • 10
  • 14