为什么 std::less 比 "<" for pointers?

问题描述 投票:0回答:1

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*>());

然后我检查了 libc++ 中的

std::less 实现(为了可读性而修改了代码块):

template <class _Tp>
struct less {
    constexpr bool operator()(const _Tp& __x, const _Tp& __y) const
        {return __x < __y;}
};

我发现

std::less
也使用
<
来完成工作,那么为什么
<
对于指针来说是未定义的,而
std::less
却不是?我为什么要使用它?

c++ std comparison-operators unspecified-behavior
1个回答
18
投票

因为

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

此外,指针上的

<
不一定实现严格弱排序,而
std::less
(通过专门化 - 您发布的内容不是
std::less
的“全部”!) 需要 :

任何指针类型的 std::less 特化都会产生严格的全序,即使内置运算符< does not.

简而言之:

std::less
适用于任何支持小于比较的东西。

© www.soinside.com 2019 - 2024. All rights reserved.