STL学习笔记6 -- 栈stack 、队列queue 和优先级priority_queue 三者比较

  栈stack  、队列queue  和优先级priority_queue 三者比较

  默认下stack 和queue 基于deque 容器实现,priority_queue 则基于vector 容器实现。

  stack 先进后出

  queue 先进先出

  priority_queue 按优先级出队

  代码示例如下:

 1 #include "iostream"
 2 using namespace std;
 3 #include "string"
 4 #include "stack"
 5 #include "queue"
 6 
 7 int main()
 8 {
 9     //first in last out
10     stack <int> stack1;
11     stack1.push(12);
12     stack1.push(145);
13     stack1.push(233);
14     cout<<"pop:"<<stack1.top()<<endl;//取得栈顶元素233
15     stack1.pop();//移除元素
16     if (stack1.empty())
17     {
18         cout<<"The stack is empty!"<<endl;
19     }
20     cout<<"元素个数"<<stack1.size()<<endl;
21     cout<<"**************************************"<<endl;
22     //////////////////////////////////////////////////////////////////////////
23     //first in first out
24     queue <int> queue1;
25     queue1.push(111);
26     queue1.push(222);
27     queue1.push(333);
28     cout<<"font:"<<queue1.front()<<endl;//111
29     cout<<"back:"<<queue1.back()<<endl;//333
30     if (queue1.empty())
31     {
32         cout<<"The queue is empty!"<<endl;
33     }
34     cout<<"元素个数"<<queue1.size()<<endl;
35     cout<<"**************************************"<<endl;
36     //////////////////////////////////////////////////////////////////////////
37     // Priority Queues(优先队列),从大到小
38     priority_queue <string> queue2;
39     queue2.push("aaaa");
40     queue2.push("dddd");
41     queue2.push("cccc");
42     cout<<"top:"<<queue2.top()<<endl;//结果是dddd
43     if (queue2.empty())
44     {
45         cout<<"The queue is empty!"<<endl;
46     }
47     cout<<"元素个数"<<queue2.size()<<endl;
48     cout<<"**************************************"<<endl;
49 
50     getchar();
51     return 0;
52 }

 

posted @ 2013-09-26 17:58  struggle_time  阅读(378)  评论(0编辑  收藏  举报