fork download
  1. #include <map>
  2. #include <string>
  3. #include <algorithm>
  4. #include <iterator>
  5. #include <iostream>
  6.  
  7. // define the Sorter template class. If sortdir == true, then we sort ascending
  8. template <bool sortdir = true>
  9. struct Sorter
  10. {
  11. bool operator()(const std::string& left, const std::string& right)
  12. {
  13. if ( sortdir )
  14. return left < right;
  15. return left > right;
  16. }
  17. };
  18.  
  19. // our test maps
  20. typedef std::pair<unsigned long long, unsigned long long> mapDataType;
  21.  
  22. // ascending map
  23. std::map<std::string, mapDataType, Sorter<>> myMap = {{"abc", {0,0}}, {"def",{0,1}}};
  24.  
  25. // descending map
  26. std::map<std::string, mapDataType, Sorter<false>> myMap2; // descending map
  27.  
  28. // sample program
  29. using namespace std;
  30. int main()
  31. {
  32. // copy to descending map
  33. std::copy(myMap.begin(), myMap.end(), std::inserter(myMap2, myMap2.begin()));
  34.  
  35. cout << "The keys in ascending map are:\n";
  36. for (auto it : myMap)
  37. cout << it.first << "\n";
  38. cout << "\nThe keys in descending map are:\n";
  39. for (auto it : myMap2)
  40. cout << it.first << "\n";
  41.  
  42. }
  43.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
The keys in ascending map are:
abc
def

The keys in descending map are:
def
abc