为什么std ::没有比“<"更好? [英] Why is std::less better than "<"?

查看:53
本文介绍了为什么std ::没有比“<"更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++入门,第5部分,14.8.2,将库函数对象与算法配合使用:

C++ primer, 5th, 14.8.2, Using a Library Function Object with the Algorithms:

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实现:

Then I checked the std::less implementation:

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还使用运算符<做这项工作,为什么<是未定义的,并且库保证对指针类型的定义较少,为什么建议不要使用std:less,为什么要优于<.

I found out that std::less also use operator < to do the work, so why < is undefined and library guarantees that less on pointer types is well defined, why is std:less recommended, and why is std::less better than <.

推荐答案

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

Because < isn't always operator<(). Only classes have operator functions, so your suggestion would not work for the built-in types.

此外,指针上的< 不一定实现严格的弱排序,而 std :: less (通过专门化—发布的内容并不一定 std :: less 的全部"!)必填到:

Furthermore, < on pointers doesn't necessarily implement a strict-weak ordering, whereas std::less (via specialisation — what you posted isn't "all" of std::less!) is required to:

std :: less的特殊化对于任何指针类型都会产生严格的总顺序,即使内置运算符<没有.

A specialization of std::less for any pointer type yields a strict total order, even if the built-in operator< does not.

简而言之: std :: less 适用于支持小于比较的任何事物.

In short: std::less works for anything that supports a less-than comparison.

这篇关于为什么std ::没有比“&lt;"更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆