使用更大的比较器初始化映射

Initializing map with greater comparator

本文关键字:比较器 初始化 映射      更新时间:2023-10-16

我很困惑为什么使用 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::mapstd::map<double, std::queue<something>, std::greater<>>