gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:33:25 25 4
gpt4 key购买 nike

<分区>

所以我有点知道我不能使用 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;
}

但是还是编译不出来...

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

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