1

I am trying to modify a list size (erase elements) inside a foor loop and as the iterarions go reduce de foor loop range:

list<int>::iterator it, it2;
int pairs = 0;
for(it = lista.begin(); it != lista.end(); it++ )
{
    int count =0;
    for(it2 = lista.begin(); it2 != lista.end(); it2++)
    {
        if (*it2 == *it)
        {
        it2 = lista.erase(it2);
        count = count + 1;
        }
    }
    if (count/2 >= 2)
    pairs = int(count/2) + pairs;
}
cout << pairs;

when I run the code above I keep getting the error

non-dereferenceable iterator for std::list

The problem is with the first iterator (it), it seems that it gets lost when erasing an element from the list with it2.

Kind regards

Angel
  • 11
  • 2
  • 1
    `if (it2 == it)` -- Comparing two iterators doesn't make sense in this context. What are you trying to compare? The values the iterators are pointing to? If so, that line doesn't do it. – PaulMcKenzie Jul 08 '20 at 00:43
  • Apart from the issue you are having, the code has a logical problem: `it2 == it` compares two iterators, not two list items pointed to by the iterators. If you are looking for pairs of identical numbers at distinct positions, you should use `*it2 == *it && it2 != it`. – Sergey Kalinichenko Jul 08 '20 at 00:43
  • Does this answer your question? [Segmentation fault in std::vector::erase() in Visual C++](https://stackoverflow.com/questions/7516145/segmentation-fault-in-stdvectorerase-in-visual-c) – yuri kilochek Jul 08 '20 at 00:45
  • What does `it2++` mean after you've performed `lista.erase(it2)`? Perform some research about erasing from a list while iterating over it. There's probably an example and explanation on the cppreference documentation for `erase`... – Asteroids With Wings Jul 08 '20 at 00:48
  • [Yep, there is](https://en.cppreference.com/w/cpp/container/list/erase). Read documentation for the things you use. – Asteroids With Wings Jul 08 '20 at 00:49
  • *non-dereferenceable iterator for std::list* -- Do you know *why* you are getting this error, or you know why but want to find another way to accomplish the loop? – PaulMcKenzie Jul 08 '20 at 00:49
  • (You'll need to cleverly reset `it`, too; there's probably a better way to accomplish whatever it is that you're trying to accomplish) – Asteroids With Wings Jul 08 '20 at 00:55
  • search for erase remove idiom, although if you're just wanting to remove duplicates, use a set – Kenny Ostrom Jul 08 '20 at 01:15

0 Answers0