Std :: multimap and equal_range

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)); 
+4
source share
1 answer

erase returns an iterator, so reset your iterator to this and will continue to operate.

Just insert a new key, erasing the original

http://ideone.com/0Pr6Qc :

 #include <iostream> #include <map> void printMultimap(const std::multimap<int, int>& multiMap) { std::cout << "MultiMap:\n"; for (const auto& pair : multiMap) { std::cout << pair.first << ":" << pair.second << "\n"; } } int main() { std::multimap<int, int> 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)); printMultimap(multiMap); auto range = multiMap.equal_range(2); for (auto iterator = range.first; iterator != range.second;) { if (iterator->second != 4) { multiMap.insert(std::make_pair(-1, iterator->second)); } iterator = multiMap.erase(iterator); } printMultimap(multiMap); return 0; } 
+5
source

All Articles