简体   繁体   English

operator <overload for std :: map的int类型比较? (我希望它按降序排序..)

[英]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.

相关问题 std :: sort降序与运算符重载 - std::sort descending order with operator overloading 当使用std :: map我应该重载operator ==的密钥类型? - When using std::map should I overload operator== for the key type? 关于std :: list,如果我想按降序排序,可以简单地调用“ mylist.sort(&gt;)”吗? - Regarding std::list, if I want to sort in descending order can I simply call “mylist.sort(>)”? 运算符==重载中的模板类型比较 - Template type comparison in operator == overload 是否可以使用pair std:string和std :: vector重载&lt;&lt; operator for std :: map <int> ? - Would it be possible to overload << operator for a std::map with pair std:string and std::vector<int>? std::pair 的重载运算符&gt;&gt;<int, int> - Overload operator>> for std::pair<int, int> 如何正确重载&lt;&lt;操作符以返回int值? - How do I overload the << operator correctly in order to return an int value? 如何为 std::map 重载插入运算符 &gt;&gt; in<const int, int> C++?</const> - How to overload insertion operator >> in for std::map<const int, int> C++? std :: sort_heap降序 - std::sort_heap in descending order 错误:地图中的operator =含糊不清的重载 <int, std::basic_string<char> &gt; :: Elem :: t3 = 0 - error: ambiguous overload for operator= in Map<int, std::basic_string<char> >::Elem::t3 = 0
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM