I'm having headaches with the std::multimap container, and I want to know what will be the right way to achieve my goal. Basically, here is my SSCCE :
#include <iostream> #include <map> int main () { typedef std::multimap<int, int> CollectionType; typedef std::pair<CollectionType::iterator, CollectionType::iterator> RangeType; CollectionType multiMap; multiMap.insert(std::make_pair(1, 1)); multiMap.insert(std::make_pair(1, 2)); multiMap.insert(std::make_pair(2, 3)); multiMap.insert(std::make_pair(2, 4)); multiMap.insert(std::make_pair(2, 5)); multiMap.insert(std::make_pair(3, 1)); RangeType range = multiMap.equal_range(2); for (CollectionType::iterator iterator = range.first; iterator != range.second; ++iterator) { if (iterator->second == 4) { //multiMap.erase(iterator);//ISSUE 1 } else { //iterator->first = -1;//ISSUE 2 } } return 0; }
As you can see above, I need to select the multimap range for the given key, and then:
- I need to remove specific rows from a range
- I need to change the key of other rows from a range
Regarding 1, since " references and iterators to erased elements are invalid ", how can I remove these elements? Do I have to click specific iterators in a container and iterate over it after the loop ends? I saw this answer , but it seems a bit hacky / ugly / error prone / etc ...
As for 2, since the “dumb” approach will not (obviously) work, what would be a good approach to achieve what I need? I could remove the elements and insert new ones in their places as soon as I solve problem 1, but can this not ruin the iteration if, for example, I mistakenly insert an element with the same key as the one I just deleted? ..
int second = iterator->second; localEdges.smarter_erase(iterator); localEdges.insert(std::make_pair(-1, second));
source share