gpt4 book ai didi

c++ - 在 priority_queue 的自定义类中重载比较运算符

转载 作者:行者123 更新时间:2023-11-30 04:42:11 26 4
gpt4 key购买 nike

我正在尝试使用 priority_queue 创建一个“number”的最小堆。 “number”是我定义的一个类,它有三个私有(private)变量:

int value;           //This holds the value to be read in the heap
vector<int> list; //This holds the vector where the value is gotten from
size_t index; //This holds the index of the vector that is referenced

我在这里唯一关心的私有(private)变量是“值”。

我重载了 < 和 > 运算符作为 priority_queue 的先决条件(我认为同时执行这两个操作有点过分,但我在这里学习):

bool operator <(const number &x) {
return (value < x.value);
}

bool operator >(const number &x) {
return (value > x.value);
}

我的优先级队列声明在这里:

priority_queue<number, vector<number>, greater<number>> heap;

每当我尝试编译我的程序时,我都会收到此错误:

c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\stl_function.h:376:20: error: no match for 
'operator>'
(operand types are 'const number' and 'const number')
{ return __x > __y; }
~~~~^~~~~
In file included from main.cpp:18:0:
number.h:59:7: note: candidate: bool number::operator>(const number&) <near match>
bool operator >(const number &x) {
^~~~~~~~

我不明白为什么编译器不能使用我在“数字”类中重载的 > 运算符。有谁知道为什么会发生此错误?另外,我不确定是否需要发布更多代码来解决这个问题,因为我是使用 priority_queue 的新手。如果我这样做,请告诉我。

最佳答案

我在评论中被告知我需要在我的运算符之后添加一个常量。

bool operator <(const number &x) const {
return (value < x.value);
}

bool operator >(const number &x) const {
return (value > x.value);
}

关于c++ - 在 priority_queue 的自定义类中重载比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58867203/

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