fork download
  1. #include <map>
  2. #include <string>
  3. #include <iostream>
  4.  
  5. int main() {
  6. // Creating & Initializing a map of String & Ints
  7. std::map<std::string, int> mapOfWordCount = { { "aaa", 10 }, { "ddd", 41 },
  8. { "bbb", 62 }, { "ccc", 10} };
  9.  
  10. // Invert and filter the original map.
  11. std::map<int, std::string> inverseMap;
  12. for(const auto &kv : mapOfWordCount)
  13. inverseMap.insert(make_pair(kv.second, kv.first));
  14.  
  15. // Print the inverted map (value before key to keep original key-value order).
  16. for(const auto& kv : inverseMap)
  17. std::cout << "{ \"" << kv.second << "\", " << kv.first << " }" << std::endl;
  18.  
  19. // Optional: Invert the inverted map again to get a std::map<std::string, int>.
  20. std::map<std::string, int> setOfWords;
  21. for(const auto& kv : inverseMap)
  22. setOfWords[kv.second] = kv.first;
  23.  
  24. // Print the (sorted) target map.
  25. std::cout << std::endl;
  26. for(const auto& kv : setOfWords)
  27. std::cout << "{ \"" << kv.first << "\", " << kv.second << " }" << std::endl;
  28. }
Success #stdin #stdout 0s 4308KB
stdin
Standard input is empty
stdout
{ "aaa", 10 }
{ "ddd", 41 }
{ "bbb", 62 }

{ "aaa", 10 }
{ "bbb", 62 }
{ "ddd", 41 }