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.
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.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With