模板:优先队列(priority_queue)

 1 #include <iostream>

 2 #include <cstdio>

 3 #include <queue>

 4 #include <vector>

 5 

 6 using namespace std;

 7 

 8 struct node

 9 {

10     int priortity;

11     int value;

12 

13     friend bool operator<(node n1,node n2)

14     {

15         return n1.priortity < n2.priortity; // < 从大到小 , > 从小到大

16     }

17 };

18 

19 int main()

20 {

21     const int len = 5;

22     int i;

23     int a[len] = {3,5,9,6,2};

24 

25     //example 1:

26     priority_queue<int> qi;

27 

28     for(i = 0; i < len; ++i)

29     {

30         qi.push(a[i]);

31     }

32 

33 

34     for(i = 0; i < len; ++i)

35     {

36         cout << qi.top() << endl;

37         qi.pop();

38     }

39 

40     //example 2:

41     priority_queue<int,vector<int>,greater<int> > qi2; // greater从小到大,less从大到小

42 

43     for(i = 0; i < len; ++i)

44     {

45         qi2.push(a[i]);

46     }

47 

48     for(i = 0; i < len; ++i)

49     {

50         cout << qi2.top() << endl;

51         qi2.pop();

52     }

53 

54     //example 3:

55     priority_queue<node> qn;

56     node b[len];

57     b[0].priortity = 6; b[0].value = 1;

58     b[1].priortity = 1; b[1].value = 5;

59     b[2].priortity = 2; b[2].value = 3;

60     b[3].priortity = 8; b[3].value = 2;

61     b[4].priortity = 1; b[4].value = 4;

62 

63     for(i = 0; i < len; ++i)

64     {

65         qn.push(b[i]);

66     }

67 

68     for(i = 0; i < len; ++i)

69     {

70         cout << qn.top().priortity << "\t" << qn.top().value << endl;

71         qn.pop();

72     }

73 

74     return 0;

75 }

参考文献:

http://wenku.baidu.com/link?url=_Y5TTAR5M4O2Eakp3lckzhc9ZkvGKp0Bqk-iSgxzUQOL5kuxGwwLZlFO1cq4ZqqvJV1HoNgurOftPRJvKp9Ng3S83c43tS1tQp0jxFHBp-u

你可能感兴趣的:(Queue)