我設計了一個優先隊列,但它不適用於某些測試用例。優先級隊列不能很好地與compare()
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
template <class T1, class T2>
class priorityQueue {
private:
vector<T1> dataContainer;
class Compare {
public:
// Compare two elements .
bool operator()(const T1& a, const T1& b) const {
return a > b;
}
};
public:
priorityQueue(vector<T1>& myV) : dataContainer(myV) {
make_heap(dataContainer.begin(), dataContainer.end(), Compare());
}
bool empty() const { return dataContainer.empty(); }
// get the size of the queue
size_t size() const { return dataContainer.size(); }
// get the element with the highest priority in the queue
T1& top(){ return dataContainer.front();}
// push an element into the qeueu
void enQueue(T1& element) {
dataContainer.push_back(element);
push_heap(dataContainer.begin(), dataContainer.end(), Compare());
}
// pop the element with the highest priority in the qeueu
void deQueue() {
pop_heap(dataContainer.begin(), dataContainer.end(), Compare());
dataContainer.erase(dataContainer.begin());
}
void printQ() {
typename vector<T1>::iterator itr ;
cout << "the priorityQueue is : " << endl ;
for (itr = dataContainer.begin(); itr != dataContainer.end(); ++itr) {
cout << *itr << "\t";
}
cout << endl ;
}
};
int main() {
vector<int> aa;
int a[4] = {5, 8, 3, 2};
aa.assign(a, a+4);
priorityQueue<int, bool> myQ(aa);
myQ.printQ();
return 0;
}
比較類不能改變優先順序。
a > b
的輸出應爲2 3 5 8
。
UPDATE的問題已經解決了,感謝
什麼是實際輸出?在問題中使用「a b」,哪一個? –
對不起,這是一個錯字,應該是a> b,輸出是2 5 3 8,它可以在linux上運行,應該是8 5 3 2。謝謝。 – user1002288
爲什麼標記爲C? – GManNickG