[英]How to sort a map with its maximum value of key in C++
I am trying to sort a map with definition map<double,deque<Object>>
with the maximum value of double (key) but by default the map takes the minimum value of key . 我试图用定义
map<double,deque<Object>>
对映射进行排序map<double,deque<Object>>
最大值为double(key),但默认情况下映射采用key的最小值。 How can I sort the map by the maximum value of key which is a double . 如何通过双键的最大值对地图进行排序。
Thanks in advance 提前致谢
You can't re-sort a map, but you can use a map that sorts itself in the reverse order to the default. 您无法对地图进行重新排序,但可以使用以相反顺序对自身进行排序的地图。
std::map
has a third template parameter for the comparison functor used for ordering. std::map
具有用于排序的比较仿函数的第三个模板参数。 The default is std::less<key_type>
. 默认值为
std::less<key_type>
。 You can trivially use the reverse ordering by using std::greater<key_type>
: 您可以使用
std::greater<key_type>
使用反向排序:
std::map<double, std::deque<Object>, std::greater<double>> m;
The closest you can come to sorting a map is to create a new one based on an original with different sorting criteria: 您最接近排序地图的方法是根据具有不同排序条件的原始文件创建一个新的:
std::map<double, std::deque<Object>> orig = ....;
std::map<double, std::deque<Object>, std::greater<double>> m(orig.begin, orig.end());
map is a key-value pair, key has to be unique in general, if not then value type could be a vector or list instead of a single typed elemental value like hash_map> where MyType is struct or a class. map是键值对,键一般必须是唯一的,否则则value类型可以是向量或列表而不是单个类型的元素值,如hash_map>其中MyType是struct或类。 While querying you search with the key to retrieve the value, no notion of sorting.
在查询时使用键来搜索值,但没有排序的概念。 Otherwise, you need to use a vector instead.
否则,您需要使用向量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.