[英]operator< overload for std::map's int type comparison? (I want it to sort in descending order..)
I have encountered a problem that I want to define a map, that is sorted internally by the first's descending order. 我遇到了一个问题,我想定义一个地图,它按照第一个降序排列内部。 if the first is not a primary type, like if it's a class, I can just overload the "<" within that class, but I don't know how to deal with the int type.
如果第一个不是主类型,就像它是一个类,我可以重载该类中的“<”,但我不知道如何处理int类型。 Any suggestion?
有什么建议吗?
Thanks a lot!! 非常感谢!!
Add a comparator: 添加比较器:
#include <functional>
map<int, value_type, greater<int>> m;
The default is less<int>
. 默认值
less<int>
。
You can specify a comparator when you create the map (it's an optional constructor argument). 您可以在创建映射时指定比较器(它是可选的构造函数参数)。
eg: 例如:
bool my_compare(int x, int y) { return y < x; }
std::map<int,T,bool(*)(int,int)> my_map(my_compare);
Notice that I've needed to explicitly specify a 3rd template parameter as well. 请注意,我还需要明确指定第3个模板参数。
[ Note: I would strongly advise that you don't overload the <
operator to perform >
... ] [ 注意:我强烈建议您不要重载
<
运算符来执行>
... ]
查看std :: less实现: http : //www.cplusplus.com/reference/std/functional/less/您可以编写自己的比较器并将其与map一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.