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

2020-02-26 14:29发布

How cal I use std::map container with key value in descending order.

As an example, if insert the following items:

[2 , 5]
[1 , 34]
[3 , 67]

They will be ordered in the map like:

position 0: [1, 34]
position 1: [2, 5]
position 2: [3, 67]

I can iterate through the map reversely, but suppose the next time I am inserting [-1 , 60]. Will it be placed at the first position?

2条回答
时光不老,我们不散
2楼-- · 2020-02-26 15:12

std::map is already sorted, so you only need to traverse the map using a reverse_iterator.

A map, however, is not an array. There's no such thing as "the n-th position" in a map. (std::map is most commonly implemented using some sort of binary search tree.) If you absolutely, inevitably need to specify order manually, then use a std::vector<std::pair>.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-02-26 15:18

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]
查看更多
登录 后发表回答