C++ std::map items in descending order of keys

Use a custom comparator when the default order doesn’t do it for you.
You pass it as the third template parameter ( that’s normally defaulted to std::less<KeyType> ).
In your case, you can use std::greater:

std::map<int, int, std::greater<int> > m;

Example code:

#include <map>
#include <iostream>
#include <functional>

int main() {
  std::map<int, int, std::greater<int>> m { {-1, 77}, {0, 42}, {1, 84} };
  for (const auto& p : m)
    std::cout << '[' << p.first << ',' << p.second << "]\n";
}

Resulting output:

[1,84]
[0,77]
[-1,42]

Leave a Comment