运算符<的用途是什么?
What is the use of operator<?
在下面的代码片段中,如果有人能澄清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<
解剖显示:
- 认为
lastDelay
成员较低的对象是较小的对象 - 对于具有相同
lastDelay
s的对象,它认为返回低getId()
的对象是较小的对象。
可能不存在RankedFace
s之间的实际代码比较。实现小于操作符的动机可能是小于操作符需要在任何关联容器或无序关联容器中的键中使用RankedFace
。
相关文章:
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- "operator()"在重载运算符方法中是什么意思,在priority_queue(STL)中用作C++中的比较器?
- 是什么让一些命名函数/运算符与众不同?
- C++,()运算符重载,它的工作是什么
- std::set<Key,Compare,Allocator>::find() 函数使用"<"运算符而不是"=="运算符背后的直觉是什么?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- c++运算符重载-我实际返回的操作数类型是什么
- 这个typedef和转换运算符语法是什么意思
- 运算符和返回类型是什么意思?
- 双标具有下标运算符的原因是什么?
- 统一初始化是隐式发生的,即使 int 强制转换运算符是使用 explicit 关键字声明的.原因是什么?
- _bstr_t::运算符=是什么意思?
- Python的"in"运算符的C++等价物是什么?
- 将强制转换运算符重载到 std::map 的正确语法是什么
- typeid 运算符忽略 cv 限定符背后的理由是什么?
- 初始化中的模板转换运算符类型推导规则是什么?
- 运算符在C++" "是什么?
- "<<"和">>"运算符的名称是什么?
- 此代码运算符超载中的错误是什么?
- 将多个值与同一变量进行比较时'!='运算符最简洁的方法是什么?