gpt4 book ai didi

c++ - C++ 中的 operator() 和 operator< 有什么区别?

转载 作者:搜寻专家 更新时间:2023-10-31 00:39:20 27 4
gpt4 key购买 nike

每当我有我想要比较的 C++ 实体时,我只是实现 operator< .然而,阅读其他人的代码我发现同样可以通过实现 operator() 来实现。 .

两者有什么区别?什么时候应该使用这些运算符?

最佳答案

operator<是定义比较运算符的规范方式:

struct A { /* some members */ };
struct B { /* some members */ };

// comparison operator
bool operator<(const A&, const B&);

这为您提供了常规用法:

int main()
{
A a;
B b;

const bool result = (a < b);
}

您看到的是人们创建仿函数;也就是说,整个类唯一目的是包装比较。为了使这些看起来有点像调用代码的函数,他们使用 operator() :

struct A { /* some members */ };
struct B { /* some members */ };

// comparison functor
struct comparator
{
bool operator()(const A&, const B&);
};

这为您提供了与我之前的示例等效的代码中不太常规的用法:

int main()
{
A a;
B b;

comparator c;
const bool result = c(a,b);
}

但是,您不会将其用于此目的。仿函数用于传递给算法(特别是在通用代码中)。它们还具有能够保持状态 的额外好处,因为您可以使用构造函数参数。这使它们比简单的函数指针更灵活。

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);
}

关于c++ - C++ 中的 operator() 和 operator< 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16339249/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com