为什么 std::less 比 "<" 好?
Why is std::less better than "<"?
C++ 入门,第 5 期,14.8.2,将库函数对象与算法一起使用:
vector<string *> nameTable; // vector of pointers
// error: the pointers in nameTable are unrelated, so < is undefined
sort(nameTable.begin(), nameTable.end(),
[](string *a, string *b) { return a < b; });
// ok: library guarantees that less on pointer types is well defined
sort(nameTable.begin(), nameTable.end(), less<string*>());
然后我检查了 std::less 实现:
template<typename _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x < __y; }
};
我发现 std::less 也使用运算符 < 来完成工作,那么为什么 < 未定义并且库保证 less 指针类型定义明确,为什么推荐 std:less,以及为什么 std::less 比 <.
好
因为 <
并不总是 operator<()
。只有 类 具有运算符函数,因此您的建议不适用于内置类型。
此外,指针上的<
不一定实现严格弱排序,而std::less
(通过专业化——你发布的不是"all" of std::less
!) is required to:
A specialization of std::less for any pointer type yields a strict total order, even if the built-in operator< does not.
简而言之:std::less
适用于任何支持小于比较的东西。
C++ 入门,第 5 期,14.8.2,将库函数对象与算法一起使用:
vector<string *> nameTable; // vector of pointers
// error: the pointers in nameTable are unrelated, so < is undefined
sort(nameTable.begin(), nameTable.end(),
[](string *a, string *b) { return a < b; });
// ok: library guarantees that less on pointer types is well defined
sort(nameTable.begin(), nameTable.end(), less<string*>());
然后我检查了 std::less 实现:
template<typename _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x < __y; }
};
我发现 std::less 也使用运算符 < 来完成工作,那么为什么 < 未定义并且库保证 less 指针类型定义明确,为什么推荐 std:less,以及为什么 std::less 比 <.
好因为 <
并不总是 operator<()
。只有 类 具有运算符函数,因此您的建议不适用于内置类型。
此外,指针上的<
不一定实现严格弱排序,而std::less
(通过专业化——你发布的不是"all" of std::less
!) is required to:
A specialization of std::less for any pointer type yields a strict total order, even if the built-in operator< does not.
简而言之:std::less
适用于任何支持小于比较的东西。