Reputation: 2506
I was trying to remove an element from a std::multimap while I am looping over it in a thread that manipulates it . I used erase function in the following ways
When I do this
//mItr is base iterator which loops over the multimap
std::multimap<std::string, std::string>::iterator tmpItr = ++mItr;
healthyQ.erase(mItr);
mItr = tmpItr;
so that I can have validated iterator after erasing the element from multimap, the program stalls in erase() call . So I used it in the following way to get the next valid iterator :
mItr = healthyQ.erase(mItr);
It worked. It consumed a lot of time and I am still not sure where the problem can be
Upvotes: 0
Views: 72
Reputation: 76297
The second way is exactly how it is supposed to work
When you hold an iterator to a tree-based container and you erase it, it alters the pointers between the various nodes pointing to this node (and others). Even if you would know exactly what this node is (through the iterator), you are left with no indication what is the next node (and consequently, the next iterator). Because of this, the erase
method first finds the next node, performs the erase, and then returns an iterator to this next node.
You can see here how removal works in a red-black tree.
Upvotes: 3
Reputation: 15824
You invalidated the iterator by calling erase()
function. So when you capture the iterator returns from erase()
and reuse later you are properly handling the iterator and avoiding iterator invalidation.
Upvotes: 1