The proper way to iterate is to use iterators. However, I think by erasing, the iterator is invalidated.
Basically what I want to do is:
for(iterator it = begin; it != end; ++it)
{
if(it->somecondition() )
{
erase it
}
}
How could I do this without v[i] method?
Thanks
struct RemoveTimedEvent
{
bool operator()(const AguiTimedEvent& pX, AguiWidgetBase* widget) const
{
return pX.getCaller() == widget;
}
};
void AguiWidgetContainer::clearTimedEvents( AguiWidgetBase* widget )
{
std::vector<AguiTimedEvent>::iterator it = std::remove_if(timedEvents.begin(),
timedEvents.end(), RemoveTimedEvent());
timedEvents.erase(it, timedEvents.end());
}
erase()returns a new iterator:Note that we can no longer compare it against a precalculated end, because we may erase it and therefore invalidate it. We must get the end explicitly each time.
A better method might be to combine
std::remove_ifanderase(). You change from being O(N2) (every element gets erased and shifted as you go) to O(N):Where
predis your removal predicate, such as:In your case, you can make it pretty general:
Note lambda’s exist to simplify this process, both in Boost and C++11.