【问题标题】:Overloading comparison operators in custom class for priority_queue在priority_queue的自定义类中重载比较运算符
【发布时间】:2019-11-14 22:02:53
【问题描述】:

我正在尝试使用priority_queue 创建一个“数字”的最小堆。 “数字”是我定义的具有三个私有变量的类:

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

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

我重载了 运算符作为优先队列的先决条件(我认为两者都做有点过头了,但我在这里学习):

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 &gt;(const number &amp;x) -> bool operator &gt;(const number &amp;x) const&lt; 相同,它正在尝试使用 const 对象和 const 参数进行调用。
  • 不要忘记 const 的正确性。如果您的成员函数没有修改任何内容,则应默认将其标记为 const 以获取编译器强制执行。
  • 我添加了 const,它现在似乎可以编译了。感谢您的意见,但我不明白为什么我的程序的编译完全取决于将 const 添加到函数中。
  • @Powerracer251 std::greater 的签名是 operator()( const T&amp; lhs, const T&amp; rhs )。由于对象现在是“const”,因此您只能在其上调用 const 限定函数。
  • @NathanOliver 我明白了。谢谢你告诉我,我还是很喜欢这种东西。

标签: c++ priority-queue min-heap


【解决方案1】:

我在 cmets 中被告知我需要在我的运算符之后添加一个 const。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多