本文共 2522 字,大约阅读时间需要 8 分钟。
priority_queue为复合结构排序:
1 #include2 #include 3 4 using namespace std; 5 struct Node{ 6 int x; 7 string y; 8 Node( int a= 0, string b = "" ): 9 x(a), y(b) {}10 };11 bool operator<( Node a, Node b ){ // 注意这里的顺序和sort()里面的谓词函数不一样!12 // bool为真的 优先级小 13 if( a.x == b.x ) return a.y < b.y;14 return a.x < b.x; 15 }16 //自定义重载小于操作符 17 int main(){18 /********************************************19 对于自定义类型,则必须自己重载 operator< 20 自定义类型重载 operator< 后,声明对象时就可以只带一个模板参数。21 看下面的例子 22 *******************************************/23 24 cout<<"自定义: "< q2; 26 priority_queue q3; 27 std::string tmp = ""; 28 29 for( int i= 10; i>0; --i ){30 tmp = tmp + "12";31 q2.push( Node(i, tmp) );32 q3.push(i);33 } 34 while( !q2.empty() ){35 cout << q2.top().x << ' ' << q2.top().y << endl;36 q2.pop();37 } 38 while( !q3.empty() ){39 cout << "q3 output: "< << endl;40 q3.pop();41 } 42 //注意上面不能这样来定义:priority_queue , greater >;43 //这样定义是错误的!!!!44 //原因是:greater 没有定义45 46 //必须定义如下函数对象,才能这样定义:47 // priority_queue , cmp >;48 /*49 struct cmp{50 bool operator() ( Node a, Node b ){51 if( a.x== b.x ) return a.y> b.y;52 53 return a.x> b.x; }54 };55 */56 return 0;57 }58 59 root@u18:~/cp/test# g++ priority.cpp -g -Wall60 root@u18:~/cp/test# valgrind --tool=memcheck --leak-check=yes ./a.out61 ==24385== Memcheck, a memory error detector62 ==24385== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.63 ==24385== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info64 ==24385== Command: ./a.out65 ==24385== 66 自定义: 67 10 1268 9 121269 8 12121270 7 1212121271 6 121212121272 5 12121212121273 4 1212121212121274 3 121212121212121275 2 12121212121212121276 1 1212121212121212121277 q3 output: 1078 q3 output: 979 q3 output: 880 q3 output: 781 q3 output: 682 q3 output: 583 q3 output: 484 q3 output: 385 q3 output: 286 q3 output: 187 ==24385== 88 ==24385== HEAP SUMMARY:89 ==24385== in use at exit: 0 bytes in 0 blocks90 ==24385== total heap usage: 20 allocs, 20 frees, 1,012 bytes allocated91 ==24385== 92 ==24385== All heap blocks were freed -- no leaks are possible93 ==24385== 94 ==24385== For counts of detected and suppressed errors, rerun with: -v95 ==24385== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
转载地址:http://wnpdx.baihongyu.com/