使用更大的比较器初始化映射
Initializing map with greater comparator
我很困惑为什么使用 std::less 比较器初始化映射有效,而 std::Greater 不起作用。
我相信我正在使用的构造函数是这个
explicit map( const Compare& comp,
const Allocator& alloc = Allocator() );
代码示例:
typedef std::map<double, std::queue<something>> mydef;
auto t1 = mydef{std::less<double>()} // works
auto t2 = mydef{std::greater<double>()} // does not ( error: no matching constructor for initialization of 'mydef' .... )
您需要考虑Compare
的定义。它取自map
的模板参数:
template<
class Key,
class T,
class Compare = std::less<Key>, // <-- here
class Allocator = std::allocator<std::pair<const Key, T>>
> class map;
因此,默认情况下,您要有效地调用构造函数:
explicit map( const std::less<Key>& comp, const std::allocator<std::pair<const Key, T>>& alloc = std::allocator<std::pair<const Key, T>>() );
这就是为什么当您构造mydef
的实例时,默认情况下只有std::less
有效。
您需要更改mydef
声明才能改用std::greater
:
typedef std::map<double, std::queue<something>, std::greater<double>> mydef;
auto t1 = mydef{std::less<double>()}; // error: no matching constructor for initialization of 'mydef' ....
auto t2 = mydef{std::greater<double>()}; // works
std::greater
是一个模板。std::greater<T>
是一种类型。比较器是std::map
的模板类型参数。
std::map<double, std::queue<something>>
使用默认的比较器类型,即std::less<double>
。这就是为什么您可以使用std:less
实例而不是任何其他比较器实例化映射的原因。
您需要在模板的实例化中指定比较对象类型std::map
:std::map<double, std::queue<something>, std::greater<>>
。
相关文章:
- 无法使用比较器初始化标准::函数
- 使用更大的比较器初始化映射
- 如何使用自定义比较器初始化类数据成员,该成员是 std::set
- 如何使用迭代器初始化地图的键字段?
- 从不同类型的容器的迭代器初始化向量
- 我应该使用类内发起器初始化静态常量数据成员还是在其类外的定义中初始化静态常量数据成员
- 通过drived类模板值通过基类构造器初始化基类数组成员变量
- 向量是否知道在由一对迭代器初始化时首先保留?
- 错误C7034:无法使用括号初始化器初始化数组
- C 用迭代器初始化向量
- 函数包装器初始化在 C++11 中是如何工作的
- 使用依赖于 "this" C++ 的比较结构初始化集合
- C++使用自定义比较函数初始化priority_queue
- std::map 迭代器初始化在C++中为零
- 在C++中使用自定义比较功能初始化多集
- OpenCV级联分类器初始化
- 用C++中的比较器初始化集合
- 使用自定义比较器模板化自定义容器
- 通过解析器初始化类
- STL:用未构造的有状态比较器初始化容器