运算符<的用途是什么?

What is the use of operator<?

本文关键字:是什么 运算符      更新时间:2023-10-16

在下面的代码片段中,如果有人能澄清bool operator<...的功能是什么,为什么它被用作一个函数?

bool operator<(const RankedFace& other) const
{
  if (lastDelay == other.lastDelay)
    return face.getId() < other.face.getId();
  return lastDelay < other.lastDelay;
}

这是用户定义类型(RankedFace我猜)的operator<的(在类中)定义

多亏了这段代码,您将能够比较两个类型为RankedFace<的对象,例如if( r1 < r2 ) // do something...

它给类型RankedFace一个小于比较(operator<)。声明;它看起来像一个成员方法。它也可以是具有以下签名的非成员方法;

bool operator<(const RankedFace& lys, const RankedFace& rhs)

通常需要在标准库关联容器(std::set等)中使用。

关联容器需要比较器来对容器中的对象排序。可以使用自定义比较器,但标准比较器是std::less,它只是一个lhs < rhs

允许客户端代码对该类型的对象(face1 < face2)使用小于比较。它通常(并非总是)与其他比较器(==!=<=等)一起实现。如果已经实现了operator<operator==,剩下的可以通过std::rel_ops实现。

这是RankedFace的小于运算符。它比较两个RankedFace对象。例如:

RankedFace foo;
RankedFace bar;
cout << foo < bar ? "foo is smaller than bar" : "bar is greater than or equal to foo";

在上面的代码中,foo < bar导致c++调用foo.operator<(bar)

RankedFace::operator<解剖显示:

  1. 认为lastDelay成员较低的对象是较小的对象
  2. 对于具有相同lastDelay s的对象,它认为返回低getId()的对象是较小的对象。

可能不存在RankedFace s之间的实际代码比较。实现小于操作符的动机可能是小于操作符需要在任何关联容器或无序关联容器中的键中使用RankedFace