【发布时间】:2016-03-02 20:21:01
【问题描述】:
为什么我不能将比较函子作为构造函数参数传递给map:
map<int, string, greater<int>> foo;
//map<int, string> foo(greater<int>()); Doesn't work
或者为什么我不能在不提供自己的比较类型的情况下传递 lambda:
map<int, string, function<bool(const int&, const int&)>> bar([](const int& lhs, const int& rhs){ return lhs > rhs; });
//map<int, string> bar([](const int& lhs, const int& rhs){ return lhs > rhs; }); Doesn't work
我希望能够声明 map<int, string> 并使用比较器构造它。为什么我不能?
【问题讨论】:
-
因为这会涉及一些类型擦除,这不是最佳的?
-
@PiotrSkotnicki 你是说函子版本?但是
map不提供比较构造函数吗? cplusplus.com/reference/map/map/map 这不正是这个目的吗? -
@JonathanMee 它用于初始化存储在地图中的实际比较器。在构造函数之外不知道其类型的情况下如何存储该比较器
-
@NathanOliver 你是说我们必须在
map模板中有类型,因为我们可以只使用一个指针?
标签: c++ templates dictionary comparator constructorargument