为什么我不能创建struct对象类型的优先级队列?

时间:2016-05-15 02:19:48

标签: c++ struct operator-overloading priority-queue

所以我知道我不能使用类型结构建立优先级队列,但我不完全理解其原因?我的意思是如果你可以创建模板类来创建自己的类型,为什么结构会有所不同?

这是我的代码在main.cpp中的样子:

#include <iostream>
#include <queue>
#include <string>

struct DATA {
    std::string key;
    int data;
};

int main() {
    std::priority_queue<DATA> priorityQ;
    DATA newItem;
    newItem.key = "apples";
    newItem.data = 3;
    priorityQ.push(newItem);
    std::cout << priorityQ.top().key << std::endl;

    std::cout << "Press the 'ENTER' key to continue...";
    std::cin.get();

    return 0;
}

出现错误:

Error   C2678   binary '<': no operator found which takes a left-hand
operand of type 'const DATA' (or there is no acceptable conversion)
TestProj    c:\program files (x86)\microsoft visual studio 
14.0\vc\include\xstddef    Line: 240    

我尝试让这个运算符重载:

bool operator<(const DATA& a, const DATA& b) {
    return a.data > b.data;
}

但它仍然无法编译......

我的问题是:是否可以将struct对象放在优先级队列中,如果没有,为什么?

2 个答案:

答案 0 :(得分:0)

你走了。

apply

直播:https://godbolt.org/g/uC6JdB

答案 1 :(得分:-2)

priority_queue数据结构要求对象响应&#39;&lt;&#39;运算符与&#39; const&#39;回报价值。 您应该将返回布尔值声明为&#34; const&#34;。

bool operator<(const DATA& a, const DATA& b) const{
     return a.data > b.data;
}