fork download
  1. #include <vector>
  2. #include <algorithm>
  3. #include <map>
  4. #include <string>
  5. #include <iostream>
  6. #include <iterator>
  7.  
  8. template <class T, class U>
  9. class sorting_map
  10. {
  11. const std::map<T, U>& s_map;
  12. public:
  13. sorting_map(const std::map<T, U>& s_ ) : s_map(s_) {}
  14. bool operator()(T x, T y) const { return s_map.at(x) < s_map.at(y); }
  15. };
  16.  
  17. using namespace std;
  18. int main()
  19. {
  20. map<string, int> tmap = {{"a", 5}, {"b", 1}, {"c", 3}, {"e", 6}, {"f", 10}, {"g", 8}};
  21.  
  22. vector<string> v = {"a", "b", "c", "f", "g"};
  23.  
  24. cout << "Before sorting: ";
  25. copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));
  26. cout << '\n';
  27.  
  28. sort(v.begin(), v.end(), sorting_map<string, int>(tmap));
  29.  
  30. cout << "After sorting: ";
  31. copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));
  32. cout << '\n';
  33.  
  34. map<string, int, sorting_map<string, int> > mymap3(tmap);
  35. mymap3["a"] = 100;
  36. mymap3["b"] = 200;
  37. mymap3["c"] = 300;
  38. for(auto i = mymap3.begin(); i!=mymap3.end(); ++i)
  39. std::cout << "mymap3[" << i->first << "] = " << i->second << '\n';
  40. }
  41.  
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
Before sorting: a b c f g 
After sorting: b c a g f 
mymap3[b] = 200
mymap3[c] = 300
mymap3[a] = 100