non-dereferenceable iterator for std::list when erasing in for loop C++

288 views Asked by At

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

0

There are 0 answers