[英]What is the difference between operator() and operator< in C++?
Whenever I have C++ entities that I want to compare I just implement operator<
. 每当我有要比较的C ++实体时,我只需实现operator<
。 However, reading other people's code I saw that the same can be achieved by implementing operator()
. 但是,阅读其他人的代码后,我发现可以通过实现operator()
来实现相同的目的。
What is the difference between the two? 两者有什么区别? When should each of these operators be used? 这些运算符何时应使用?
operator<
is the canonical way to define a comparison operator: operator<
是定义比较运算符的规范方法:
struct A { /* some members */ };
struct B { /* some members */ };
// comparison operator
bool operator<(const A&, const B&);
This gives you the conventional usage: 这为您提供了常规用法:
int main()
{
A a;
B b;
const bool result = (a < b);
}
What you've seen is people creating functors ; 您所看到的是人们在创建函子 ; that is, entire classes whose sole purpose is to wrap a comparison. 也就是说, 整个类的唯一目的是包装比较。 To make these look a bit like functions to calling code, they use operator()
: 为了使它们看起来像调用代码的函数,它们使用operator()
:
struct A { /* some members */ };
struct B { /* some members */ };
// comparison functor
struct comparator
{
bool operator()(const A&, const B&);
};
This gives you a less conventional usage in code equivalent to my previous example: 这为您提供了与我之前的示例等效的不太常规的用法:
int main()
{
A a;
B b;
comparator c;
const bool result = c(a,b);
}
However, you wouldn't use it for this. 但是,您不会为此使用它。 Functors are for passing to algorithms (particularly in generic code). 函数是用于传递给算法的(尤其是在通用代码中)。 They also have the added benefit of being able to hold state , since you have constructor arguments to play with. 它们还具有保持状态的附加好处,因为您可以使用构造函数参数。 This makes them more flexible than a simple function pointer. 这使它们比简单的函数指针更灵活。
int main()
{
std::vector<A> a(5);
B b;
comparator c;
std::sort(a.begin(), a.end(), c);
// or, simply:
std::sort(a.begin(), a.end(), comparator());
// all more easily extensible than:
std::sort(a.begin(), a.end(), &someComparisonFunction);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.