Finding and erasing an item from the STL container during iteration

During iteration over multimap I want to delete elements, but not only the element that the iterator points to.

 for (vector<int> myVec : myVectors) { auto range = myMultiMap.equal_range(myVector); for (auto it = range.first; it != range.second; ++it) { // secondPair is another element of this multimap auto secondPair = getSecondPair(it, myMultiMap); if (condition) { it = myMultiMap.erase(it); auto finder = myMultiMap.find(secondPair); // how can I delete secondPair? } } } 

Maybe this is the xy problem here, so let me explain what I need for this: what I'm trying to do is shorten the set of vector<int> . For each item there are related items of type MyPair . These related items are stored in an unordered multimedia.

 typedef unordered_multimap < vector<int>, MyPair, SomeHash > MyMultiMap; 

The set<vector <int> > element can be deleted if all related pairs in the multimag were successfully processed. This will not be successful for most of them, so most of them are expected to remain bundled. My idea was to remove elements from the multimap, and if there are no related elements in the multimag, this means that the element can be removed from the set. Here again, the problem arises of removing items from the set during iteration. Again, not only the one pointed to by the iterator.

+5
source share
1 answer

From cppreference to unordered_multimap::erase :

References and iterators to deleted elements are invalid. Other iterators and links are not invalid.

So, I think that if you get the secondPair iterator and secondPairIt != it iterator, you can safely erase secondPairIt . You must also ensure that you do not invalidate the end of the range.

 for (auto it = range.first; it != range.second;) { if (condition) { auto secondPairIt = getSecondPairIt(it, myMultiMap); // Assume this is not end if (secondPairIt != it) { if (secondPairIt == range.second) range.second = myMultiMap.erase(secondPairIt); else myMultiMap.erase(secondPairIt); } it = myMultiMap.erase(it); } else { ++it; } } 
+2
source

Source: https://habr.com/ru/post/1273144/


All Articles