I\'m writing a nodal path finding algorithm. I need to run through a multimap and delete elements out of it under certain conditions, but keep iterating through the multimap
Is it safe to erase the iterator pointer from the table before incrementing the iterator?
No, erase
will invalidate the iterator and you shouldn't increment it after that.
To do this properly, make use of the return value of erase
- the iterator following the last removed element:
std::multimap<int, int> m;
for (auto it = m.begin(); it != m.end(); ) {
if (condition)
it = m.erase(it);
else
++it;
}
In C++03, erase
returns nothing, so you have to do this manualy by saving a copy of the iterator and incrementing it before you erase the original:
std::multimap<int, int> m;
typedef std::multimap<int, int>::iterator Iter;¸
for (Iter it = m.begin(); it != m.end(); ) {
if ( /* some condition */ ) {
Iter save = it;
++save;
m.erase(it);
it = save;
} else
++it;
}
Won't this be better?
std::multimap<int, int> m;
typedef std::multimap<int, int>::iterator Iter;¸
for (Iter it = m.begin(); it != m.end(); ) {
if ( /* some condition */ ) {
Iter save = it;
++it;
m.erase(save);
} else
++it;
}