gpt4 book ai didi

c++ - 这个C++结构是什么意思?

转载 作者:太空狗 更新时间:2023-10-29 23:42:35 24 4
gpt4 key购买 nike

我得到了一个简单的 C++ 结构,如下所示:

// Functor for peak to decreasing intensity sorting
struct cmp_decr_int2
{
bool operator() (peak2 a, peak2 b)
{
return a.int2 > b.int2;
}
};

此示例中是否存在运算符重载?

最佳答案

是的。 operator() 被称为“函数调用”运算符,它允许对象像函数一样使用。这样的类称为“仿函数”。

一个常见的模式是使仿函数比较两个事物的相等性或关系,用于任何需要比较谓词的事物。 (例如,这个可以在 std::map 中使用。它会有一个像cmp_decr_int2 compare; 这样的成员,然后它可以比较两个事物之间的关系: if (compare(x, y))/* x 小于 y,根据某些指标 */)

这个特定的结构通过比较它们的 int2 成员来对两个 peak2 进行排序。最好写成:

struct cmp_decr_int2
{
// note const! vvvvv
bool operator() (peak2 a, peak2 b) const
{
return a.int2 > b.int2;
}
};

该函数应该是const,因为它不需要更改任何成员(无需更改。)const-correctness很重要。*

在许多情况下,这些仿函数用于参数本身为 const 的上下文中,因此您应该像示例中那样按值或按常量引用来获取参数。

您应该更喜欢通过常量引用而不是按值来传递类型,除非该类型是基本类型(float、unsigned int、double 等)或小于 void*。那么在大多数情况下,您将通过 const-reference:

struct cmp_decr_int2
{
// note const&: vvvvv v vvvvv v vvvvv
bool operator() (const peak2 & a, const peak2 & b) const
{
return a.int2 > b.int2;
}
};

<子>*如果这在 std::map 中用作谓词,例如,如果没有 const,则 map 将无法在 中比较两个事物>const 函数。

关于c++ - 这个C++结构是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3473543/

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