STL之priority_queue为复合结构排序

priority_queue为复合结构排序: 

 1 #include <iostream>

 2 #include <queue>

 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<<"自定义: "<<endl; 

25     priority_queue<Node> q2; 

26     priority_queue<int> 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: "<<q3.top() << endl;

40         q3.pop();

41     } 

42     //注意上面不能这样来定义:priority_queue<Node, vector<Node>, greater<Node> >;

43     //这样定义是错误的!!!!

44     //原因是:greater<node>没有定义

45 

46     //必须定义如下函数对象,才能这样定义:

47     // priority_queue<Node, vector<Node>, 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 -Wall

60 root@u18:~/cp/test# valgrind  --tool=memcheck --leak-check=yes ./a.out

61 ==24385== Memcheck, a memory error detector

62 ==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 info

64 ==24385== Command: ./a.out

65 ==24385== 

66 自定义: 

67 10 12

68 9 1212

69 8 121212

70 7 12121212

71 6 1212121212

72 5 121212121212

73 4 12121212121212

74 3 1212121212121212

75 2 121212121212121212

76 1 12121212121212121212

77 q3 output: 10

78 q3 output: 9

79 q3 output: 8

80 q3 output: 7

81 q3 output: 6

82 q3 output: 5

83 q3 output: 4

84 q3 output: 3

85 q3 output: 2

86 q3 output: 1

87 ==24385== 

88 ==24385== HEAP SUMMARY:

89 ==24385==     in use at exit: 0 bytes in 0 blocks

90 ==24385==   total heap usage: 20 allocs, 20 frees, 1,012 bytes allocated

91 ==24385== 

92 ==24385== All heap blocks were freed -- no leaks are possible

93 ==24385== 

94 ==24385== For counts of detected and suppressed errors, rerun with: -v

95 ==24385== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

 

你可能感兴趣的:(Queue)