Hee hee
Hee hee

Reputation: 31

list iterators incompatible with erasing

Here's my code:

std::list<User>::iterator it;
    while (it != allUsers.end())
    {
        if (it->getId() == userId)
        {
            allUsers.remove(*it);
            return *it;
        }
        else
        {
            it++;
        }
    }

The error I get : list iterators incompatible with erasing Why?

Upvotes: 0

Views: 128

Answers (1)

rustyx
rustyx

Reputation: 85452

You have to use erase(), not remove() to remove an element from a list using an iterator:

while (it != allUsers.end()) {
    if (it->getId() == userId) {
        auto oldvalue = *it;
        allUsers.erase(it);
        return oldvalue;
    }
    it++;
}

Upvotes: 2

Related Questions