我想創建一個對象的優先級隊列,特別是對(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