fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <vector>
  4.  
  5. std::map<int, std::vector<int>> foo(std::map<int, int> m)
  6. {
  7. std::map<int, std::vector<int>> res;
  8.  
  9. while (!m.empty())
  10. {
  11. auto it = m.begin();
  12. const auto key = it->first;
  13. auto& v = res[key];
  14.  
  15. while (it != m.end()) {
  16. auto value = it->second;
  17. v.push_back(value);
  18. m.erase(it);
  19. it = m.find(value);
  20. }
  21. }
  22. return res;
  23. }
  24.  
  25. int main()
  26. {
  27. std::map<int, int> my_map = { {2, 31}, {4, 36}, {5, 29}, {6, 24}, {24, 49},
  28. {25, 83}, {29, 63}, {36, 42}, {42, 79} };
  29.  
  30. auto res = foo(my_map);
  31.  
  32. for (const auto& p : res) {
  33. std::cout << p.first << ":";
  34. for (const auto& e : p.second) {
  35. std::cout << e << " ";
  36. }
  37. std::cout << std::endl;
  38. }
  39. }
  40.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
2:31 
4:36 42 79 
5:29 63 
6:24 49 
25:83