Priority_queue for composite Structures:
1#include <iostream>2#include <queue>3 4 using namespacestd;5 structnode{6 intx;7 stringy; 8Node (intA=0,stringb ="" ):9 x (a), Y (b) {}Ten }; One BOOL operator< (Node A, Node B) {//Note that the order here is not the same as the predicate function inside the sort ()! A //BOOL is really a small priority - if(a.x = = b.x)returnA.y <b.y; - returnA.x <b.x; the } - //Custom overload less operator - intMain () { - /******************************************** + for custom types, you must overload the operator< yourself - after the custom type overloads the operator<, the object can be declared with only one template parameter. + look at the following example A *******************************************/ at -cout<<"Custom:"<<Endl; -Priority_queue<node>Q2; -priority_queue<int>Q3; -STD::stringTMP =""; - in for(intI=Ten; I>0; --i) { -TMP = tmp +" A"; to Q2.push (Node (i, TMP)); + Q3.push (i); - } the while( !Q2.empty ()) { *cout << q2.top (). x <<' '<< q2.top (). Y <<Endl; $ Q2.pop ();Panax Notoginseng } - while( !Q3.empty ()) { thecout <<"Q3 output:"<<q3.top () <<Endl; + Q3.pop (); A } the //Note that this cannot be defined as: Priority_queue<node, Vector<node>, greater<node> >; + //this definition is wrong!!!! - //The reason is that:greater<node> is not defined $ $ //The following function object must be defined to define this: - //Priority_queue<node, Vector<node>, CMP >; - /* the struct cmp{ - bool Operator () (Node A, Node B) {Wuyi if (a.x== b.x) return a.y> b.y; the - return a.x> b.x;} Wu }; - */ About return 0; $ } - -[Email protected]:~/cp/test# g++ priority.cpp-g-Wall -[Email protected]:~/cp/test# valgrind--tool=memcheck--leak-check=yes./A. out A==24385==Memcheck, a memory error detector +==24385Copyright (C)2002- ., and GNU GPL'd, by Julian Seward et al. the==24385= = Using valgrind-3.7.0and Libvex; Rerun With-h forCopyright Info -==24385= = Command:./A. out $==24385== the Custom: the Ten A the 9 1212 the 8 121212 - 7 12121212 in 6 1212121212 the 5 121212121212 the 4 12121212121212 About 3 1212121212121212 the 2 121212121212121212 the 1 12121212121212121212 theQ3 output:Ten +Q3 output:9 -Q3 output:8 theQ3 output:7BayiQ3 output:6 theQ3 output:5 theQ3 output:4 -Q3 output:3 -Q3 output:2 theQ3 output:1 the==24385== the==24385==HEAP SUMMARY: the==24385==inchUse at exit:0bytesinch 0blocks -==24385= = Total Heap Usage: -Allocs, -Frees,1,012Bytes Allocated the==24385== the==24385= = All heap blocks were freed--no leaks is possible the==24385==94==24385= = Counts of detected and suppressed errors, rerun with:-v the==24385= = ERROR SUMMARY:0Errors from 0Contexts (suppressed:2 from 2)
The priority_queue of STL is a sort of compound structure