mardi 31 mars 2020

C++ - begin() returns the end() iterator with a non-empty list

As the question suggest, I'm having a very strange behavior with iterators and lists. So, the (class) problem asks for a function that erase all elements that meet a condition from a list and, when I tried to cover the case where I have a list where all elements are the same I found out that the last element persisted.

Here is the code:

void esborra_tots(list<Estudiant>& t, int x) {
    list<Estudiant>::iterator it;
    list<Estudiant>::iterator itend = t.end();

    for (it = t.begin(); it != t.end(); it++) {
        if ((*it).consultar_DNI() == x) {

            t.erase(it);
            if (t.empty()) return;
            else it = t.begin();
        }
    }
}

I've used itend just to see the value while debugging. Here is the session: See that the list *t* is not empty but t.begin() returns the same as t.end()

How is this possible? PD: I'm not searching for other approaches to the problem.

Aucun commentaire:

Enregistrer un commentaire