I want to iterate through a list of objects, then erase all objects from the list which meet a certain criteria. Here is an example using int type as my object:
list<int> m_list;
// Fill list with int values...
// Find ints == 4 and erase them
auto it = m_list.begin();
if (*it == 4)
{
it = m_list.erase(it);
}
while (it != m_list.end())
{
++it;
if (*it == 4)
{
it = m_list.erase(it);
}
}
This code works fine, but it seems wordy and the iterator it is still in scope after I am through with it.
I thought I should be able to use a for loop like this:
for (auto it = m_list.begin(); it != m_list.end(); ++it)
{
if (*it == 4)
{
it = m_list.erase(it);
}
}
But when the last element in the list is erased, .erase returns an iterator to the end of the list which cannot be incremented.
So is there a better way to erase? Thank you.