如果std :: greater<>,那么为什么std :: less(而不是std :: lesser<>)?

时间:2017-09-12 02:33:18

标签: c++

这显然看起来像一个语法(而且有趣?)的问题,但我希望不是。

如果我们没有std::lesser<>(而不是std::greater<>),我真的很想知道为什么我们有std::less<>?拥有greaterlessergreatless是否有意义?我问这个问题是因为我每次都搞乱它并且需要谷歌。

该标准是否遵循一些命名约定?

1 个答案:

答案 0 :(得分:4)

我要说的是,这实际上只是告知推测,该标准的作者做出了明确的选择,选择了一种方式而不是另一种方式。英语具有使人迷惑的近乎无限的能力,它有很多表达同一想法的方法

a is GREATER than b   =>   a is the GREATER value
a is LESS    than b   =>   a is the LESSER  value

但是,由于std::greaterstd::less intent 是要返回一个布尔值,指示相关条件是否为真,因此上面的左列是右要走的路。相反,如果返回更大或更小的值,则更倾向于使用右侧列。

实际上,如果您查看ISO标准(C++11 20.8.5 Comparisons /4 and /5),就会看到它们的定义方式(略有重新格式化):

template <class T> struct greater {
    bool operator()(const T& x, const T& y) const;
    typedef T first_argument_type;
    typedef T second_argument_type;
    typedef bool result_type;
};                                                   // operator() returns x > y.
template <class T> struct less {
    bool operator()(const T& x, const T& y) const;
    typedef T first_argument_type;
    typedef T second_argument_type;
    typedef bool result_type;
};                                                   // operator() returns x < y.

这些注释部分将明确地理解为“返回x比y大 ”和“返回x小于 < / strong>比y”。