Kajzer
Kajzer

Reputation: 2385

"List iterators incompatible" when trying to erase an element from the list

list<employee> remove_employees(const string& name,
                                const string& lastname) 
{
    list<employee> listOfRemoved; 
    list<employee>::iterator it; 

    for(it=employees.begin(); it != employees.end(); )
    {
        if(it->get_name() == name && it->get_lastname() ==lastname) 
        {
            listOfRemoved.push_back(*it); 
            employees.erase(it); 
        }
        else
            it++;
    }

    return listOfRemoved; 
}

I am trying to remove some employees from the class instance variable employees, and then return a new list, with only the deleted emeployees. When I try to run the program, it gives an error from the title. I know it has something to do with erasing, and pushing_back, but I just can't figure it out.

Upvotes: 4

Views: 9964

Answers (1)

hmjd
hmjd

Reputation: 122001

Change:

employees.erase(it); 

to:

it = employees.erase(it); 

Otherwise on the next iteration of the loop it will be referring to an invalid element. list::erase() returns the iterator following the last removed element.

[I had interpreted the title as a compiler error, not a runtime error.]

Upvotes: 14

Related Questions