先上代码:
#include <iostream>
#include <iterator>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
struct Node{
int x, y;
//法1:类内部重载运算符:operator<
bool operator<(const Node &b) const{
if(x==b.x) return y>b.y;
return x>b.x;
}
//法2:类内部重载运算符:operator<
/*
friend bool operator<( Node a, Node b){
if(a.x==b.x) return a.y>b.y;
return a.x>b.x;
}
*/
};
//法3:类外部重载运算符:operator<
/*
inline bool operator<( Node a, Node b){
if(a.x==b.x) return a.y>b.y;
return a.x>b.x;
}
*/
<pre class="cpp" name="code">//仿函数形式
struct cmpFun{
bool operator < (Node a, Node b){
if(a.x==b.x) return a.y>b.y;
return a.x>b.x;
}
bool cmp(const int &left, const int &right){
return left < right;
}
int main(){
priority_queue<int,vector<int>,less<int> >q;//使用priority_queue<int> q1;一样
vector<int> vecInt;
for(int i=0;i<10;i++)
{
q.push(i);
vecInt.push_back(i);
}
sort(vecInt.begin(), vecInt.end(), less<int>() );
cout << "vector" << endl;
for(size_t i=0; i!=vecInt.size(); ++i){ cout << vecInt.at(i) << endl;}
//copy(vecInt.begin(), vecInt.end(), ostream_iterator<int>(cout, " "));
cout << "priority_queue:" << endl;
cout << endl;
while(!q.empty()){
cout<<q.top()<< endl;
q.pop();
}
//Node: priority_queue
cout << "priority_queue<Node>" << endl;
priority_queue<Node> q2; //或者:priority_queue<Node, vector<Node>, cmpFun>;
for(int i=0;i<10;i++){
node.x=i;
node.y=10-i/2;
q2.push(node);
}
while(!q2.empty()){
cout<<q2.top().x <<' '<<q2.top().y<<endl;
q2.pop();
}
return 0;
}
运行结果:
vector
0
1
2
3
4
5
6
7
8
9
priority_queue:
9
8
7
6
5
4
3
2
1
0
priority_queue<Node>
0 10
1 10
2 9
3 9
4 8
5 8
6 7
7 7
8 6
9 6
从上面的代码运行结果可以发现sort(vecInt.begin(), vecInt.end(), less<int>() )与priority_queue<int,vector<int>,less<int> >的运行结果相反,都使用less<int>作为比较标准,为啥结果不同呢?
主要是由于priority_queue内部使用了Push_heap
Push_heap adds an element to a heap. It is assumed that [first, last - 1) is already a heap; the element to be added to the heap is *(last - 1).
The two versions of push_heap differ in how they define whether one element is less than another. The first version compares objects using operator<, and the second compares objects using a function object comp. The postcondition for the first version is that is_heap(first, last) is true, and the postcondition for the second version is that is_heap(first, last, comp) is true.
所以每次添加元素入堆时,如果指定的是less<int>则表示添加进去的数据作为较小值入堆,priority_queue中top()表示堆顶元素,所以是最大值。
因此两者输出结果相反的原因:指定比较标准的对象不同。sort中为集合自身元素指定;priority_queue中为新添加元素而指定。
说明:以上观点仅供个人理解使用,对其正确性不做保证。