gpt4 book ai didi

具有自定义对象的 C++ 优先级队列

转载 作者:行者123 更新时间:2023-11-27 23:46:34 25 4
gpt4 key购买 nike

我试图了解比较器如何为优先级队列工作,我做了几个测试:

测试 1:创建比较器类,并使用 priority_queue<T, vector<T>, cmp>

一切正常

测试 2:

struct test {
int a = 0;
};

bool operator<(const test& lhs, const test& rhs) {
return lhs.a < rhs.a;
}

int main()
{
priority_queue<test> pq;
}

这按预期工作。

测试 3:将测试 2 放入类中

class T{
struct test {
int a = 0;
};

bool operator<(const test& lhs, const test& rhs) {
return lhs.a < rhs.a;
}
};

编译错误:

'bool T::operator<(const T::test&, const T::test&)' must take exactly one argument

编译器似乎认为我重载了类 T 的运算符 <。如果我真的需要嵌套类,还有其他方法可以实现吗?

测试 4:重载运算符<

struct test {
int a = 0;
bool operator<(const test& rhs) {
return a < rhs.a;
}
};

int main()
{
vector<test> v;
sort(v.begin(), v.end()); // No error
set<test> s; // No error
priority_queue<test> pq; // Compiling error
}

只有 priority_queue 会抛出错误:

'passing 'const test*' as 'this' argument discards qualifiers'

我不知道为什么这适用于排序和设置但不适用于优先级队列。

最佳答案

operator<当你让它成为 class T 的成员时必须带两个参数, 它隐含地得到 this作为第三个参数,因此测试 3 中的错误:

class T {
bool operator<(const test& lhs, const test& rhs) { // error
return lhs.a < rhs.a;
}
};

要解决这个问题,请定义 operator<在嵌套 test类:

class T {
public:
struct test {
int a = 0;
friend bool operator<(const test& lhs, const test& rhs) {
return lhs.a < rhs.a;
}
};
};

或在命名空间范围内。

在测试 4 中 operator<应该是 const :

struct test {
int a = 0;
bool operator<(const test& rhs) const {
return a < rhs.a;
}
};

关于具有自定义对象的 C++ 优先级队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50092060/

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