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

左心房为你撑大大i 提交于 2019-11-29 16:19:41

问题


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?


回答1:


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]



回答2:


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>.



来源:https://stackoverflow.com/questions/22591645/c-stdmap-items-in-descending-order-of-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!