为什么我不能创建一个结构对象类型的优先级队列?

Why can't I make a priority queue of type struct objects?

所以我有点知道我不能使用 struct 类型创建优先级队列,但我不完全明白为什么?我的意思是,如果您可以创建模板 类 来制作您自己的类型,为什么结构会有所不同?

这是我的代码在 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;
}

但是还是编译不了...

我的问题是:是否可以将结构对象放入优先级队列中,如果不能,为什么?

给你。

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

struct DATA {
    std::string key;
    int data;
    // EITHER THIS
    bool operator<(const DATA & d2) const {return <your logic here>;}

};
// OR THIS
bool operator<(const DATA &d1, const DATA & d2){return <your logic here>;}


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;
}

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