Reputation: 83
For my program we i am supposed to read a list of assignments and "Prune" the bad assignments out of the list and write the new assignment list to an output file. This all works correctly except that my Prune function is for some reason counting by twos and skipping the even numbers in the vector. Now i understand using the .erase()shifts the list by one and moves the counter up by one but haven't been able to find a way around this.
void Prune()
{
for (std::vector<Assignment>::iterator i = m_Assignments.begin(); i != m_Assignments.end())
{
if (!i->IsGood())
{
i = m_Assignments.erase(i);
--i;
}
else
{
i++;
}
}
}
so far I've tried taking the counter out of the for loop and adding it to the body and also tried to decrement the counter if the object is removed form the vector.
Upvotes: 0
Views: 56
Reputation: 11807
I believe you can solve all these problems by not having to deal with loops and iterators through a useful function called std::remove_if
. This shortens your code to the following:
m_Assignments.erase(
std::remove_if(m_Assignments.begin(), m_Assignments.end(),
[](const Assignment& x)
{
return !x.IsGood();
})
, m_Assignments.end()
);
Upvotes: 1