我想创建一个对象的优先级队列,特别是对(int,int)。队列应该包含分配给它们的优先级。使用对象的优先级队列的C++
#include <iostream>
#include <queue>
using namespace std;
class saPair{
public:
int s;
int a;
double priority;
saPair(int s, int a, double priority){
this->s = s;
this->a = a;
this->priority = priority;
}
};
// the priority menmber variable determines the priority in the queue
// highest priority pair of (int, int) stays on the top
bool operator< (const saPair& x, const saPair& y) {
return x.priority < y.priority;
}
int main()
{
priority_queue<saPair> pq;
pq.push(saPair(0,0, 0.3));
pq.push(saPair(0,1, 0.1));
pq.push(saPair(0,3, 0.5));
pq.push(saPair(0,3, 5));
cout << pq.top().a << endl;
pq.pop();
cout << pq.top().a << endl;
pq.pop();
cout << pq.top().a << endl;
}
正如您所看到的,对(0,3)具有最高的优先级,因此它保持在最高位置。但是我的实现的问题是,如果我以不同的优先级再次添加(0,3)对,我会向队列中添加一个新元素,而不是替换已存在的(0,3)对的优先级。
我觉得我为我的要求选择了错误的数据结构。我试图通过定义一个新的saPair(int,int)类来为映射获取关键值,该类具有操作超载的运算符<。但即使这似乎并没有正常工作..
关于如何进行的任何建议?或修改
它是一个队列,所以没有关于唯一性的要求。也许你想要的是一套?! – Arash
是的。没有办法直接使用队列。我正在寻找一种替代数据结构。这感觉就像是一种常见的数据结构,但我无法找到一个简单的解决方案。一个对象,以及分配给该对象的相应优先级。按优先级顺序对对象进行排序。我需要一个满足这一点的数据结构。 – emperorspride188