sortとpriority_Queueの比較標準差異
3005 ワード
:
#include
#include
#include
#include
#include
using namespace std;
struct Node{
int x, y;
// 1: :operator<
bool operatorb.y;
return x>b.x;
}
// 2: :operator<
/*
friend bool operatorb.y;
return a.x>b.x;
}
*/
};
// 3: :operator<
/*
inline bool operatorb.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では、 しい を するために します.
: の は の にのみ され、その は されていない.