gpt4 book ai didi

c++ - 为什么 std::less 比 "<"好?

转载 作者:可可西里 更新时间:2023-11-01 17:38:54 28 4
gpt4 key购买 nike

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::不如 <.

最佳答案

因为 <并不总是 operator<() .只有类具有运算符函数,因此您的建议不适用于内置类型。

此外,<在指针上不一定实现严格弱排序,而 std::less (通过特化——你发布的不是 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++ - 为什么 std::less 比 "<"好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42762633/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com