sort与priority_queue的比较标准差异

先上代码:
#include 
#include 
#include 
#include 
#include 
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;
}
*/
 
  
 
  
//仿函数形式
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,less >q;//使用priority_queue q1;一样
    vector vecInt;
    for(int i=0;i<10;i++)
    {
        q.push(i);
        vecInt.push_back(i);
    }
    sort(vecInt.begin(), vecInt.end(), less() );
    cout << "vector" << endl;
    for(size_t i=0; i!=vecInt.size(); ++i){ cout << vecInt.at(i) << endl;}
    //copy(vecInt.begin(), vecInt.end(), ostream_iterator(cout, " "));
    cout << "priority_queue:" << endl;
    cout << endl;
    while(!q.empty()){
        cout<" << endl;
    priority_queue q2; //或者:priority_queue, cmpFun>;
    for(int i=0;i<10;i++){
      node.x=i;
      node.y=10-i/2;
      q2.push(node);
    }
    while(!q2.empty()){
        cout<
运行结果:
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
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() )priority_queue,less >的运行结果相反,都使用less作为比较标准,为啥结果不同呢?

主要是由于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则表示添加进去的数据作为较小值入堆,priority_queue中top()表示堆顶元素,所以是最大值。

因此两者输出结果相反的原因:指定比较标准的对象不同。sort中为集合自身元素指定;priority_queue中为新添加元素而指定。


说明:以上观点仅供个人理解使用,对其正确性不做保证。

你可能感兴趣的:(C++,sort,priority_queue,stl)