【发布时间】:2014-12-30 12:48:53
【问题描述】:
我正在处理优先级队列,我想检查如何使用可比较类比较值。这是我的代码。
#include <iostream>
#include <queue>
using namespace std;
class g {
public:
bool operator() (int a, int b) {
cout<<a<<" "<<b<<endl;
return (a > b);
}
};
int main() {
priority_queue<int,vector<int>,g> p;
p.push(2);
cout<<"CHECK1"<<endl;
p.push(4);
cout<<"CHECK2"<<endl;
p.push(8);
cout<<"CHECK3"<<endl;
p.push(1);
cout<<"CHECK4"<<endl;
while(!p.empty()) {
cout<<p.top()<<endl;
p.pop();
}
}
输出是
CHECK1
2 4
CHECK2
2 8
CHECK3
4 1
2 1
CHECK4
1
8 2
2 4
2
4 8
4
8
我看到当推入 4 时,它与 2 进行比较,当推入 8 时,它再次与 2 进行比较。但是为什么不把 8 和 4 比较呢? 有人可以帮忙吗?
【问题讨论】:
-
取决于底层数据结构 - 可能是 B-Tree 或 BST
标签: c++ priority-queue