C++ Queues(队列)

C++ Queues(队列)

C++队列是一种容器适配器,它给予程序员一种先进先出(FIFO)的数据结构。
1.back() 返回一个引用,指向最后一个元素
2.empty() 如果队列空则返回真
3.front() 返回第一个元素
4.pop() 删除第一个元素
5.push() 在末尾加入一个元素
6.size() 返回队列中元素的个数

队列可以用线性表(list)或双向队列(deque)来实现(注意vector container 不能用来实现queue,因为vector 没有成员函数pop_front!):
queue<list<int>> q1;
queue<deque<int>> q2;
其成员函数有“判空(empty)” 、“尺寸(Size)” 、“首元(front)” 、“尾元(backt)” 、“加入队列(push)” 、“弹出队列(pop)”等操作。

例:
1 int main()
2 {
3     queue<int> q;
4     q.push(4);
5     q.push(5);
6     printf("%d\n",q.front());
7     q.pop();
8 }

C++ Priority Queues(优先队列)

C++优先队列类似队列,但是在这个数据结构中的元素按照一定的断言排列有序。
1.empty() 如果优先队列为空,则返回真
2.pop() 删除第一个元素
3.push() 加入一个元素
4.size() 返回优先队列中拥有的元素的个数
5.top() 返回优先队列中有最高优先级的元素

优先级队列可以用向量(vector)或双向队列(deque)来实现(注意list container 不能用来实现queue,因为list 的迭代器不是任意存取iterator,而pop 中用到堆排序时是要求randomaccess iterator 的!):
priority_queue<vector<int>, less<int>> pq1; // 使用递增less<int>函数对象排序
priority_queue<deque<int>, greater<int>> pq2; // 使用递减greater<int>函数对象排序
其成员函数有“判空(empty)” 、“尺寸(Size)” 、“栈顶元素(top)” 、“压栈(push)” 、“弹栈(pop)”等。

例:
 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4  
 5 class T {
 6 public:
 7     int x, y, z;
 8     T(int a, int b, int c):x(a), y(b), z(c)
 9     {
10     }
11 };
12 bool operator < (const T &t1, const T &t2)
13 {
14     return t1.z < t2.z; // 按照z的顺序来决定t1和t2的顺序
15 }
16 main()
17 {
18     priority_queue<T> q;
19     q.push(T(4,4,3));
20     q.push(T(2,2,5));
21     q.push(T(1,5,4));
22     q.push(T(3,3,6));
23     while (!q.empty())
24     {
25         T t = q.top();
26         q.pop();
27         cout << t.x << " " << t.y << " " << t.z << endl;
28     }
29     return 1;
30 }
      输出结果为(注意是按照z的顺序从大到小出队的):
      3 3 6
      2 2 5
      1 5 4
      4 4 3

      再看一个按照z的顺序从小到大出队的例子:
 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 class T
 5 {
 6 public:
 7     int x, y, z;
 8     T(int a, int b, int c):x(a), y(b), z(c)
 9     {
10     }
11 };
12 bool operator > (const T &t1, const T &t2)
13 {
14     return t1.z > t2.z;
15 }
16 main()
17 {
18     priority_queue<T, vector<T>, greater<T> > q;
19     q.push(T(4,4,3));
20     q.push(T(2,2,5));
21     q.push(T(1,5,4));
22     q.push(T(3,3,6));
23     while (!q.empty())
24     {
25         T t = q.top();
26         q.pop();
27         cout << t.x << " " << t.y << " " << t.z <<  endl;
28     }
29     return 1;
30 }
      输出结果为:
      4 4 3
      1 5 4
      2 2 5
      3 3 6

      如果我们把第一个例子中的比较运算符重载为: bool operator < (const T &t1, const T &t2) { return t1.z > t2.z; // 按照z的顺序来决定t1和t2的顺序} 则第一个例子的程序会得到和第二个例子的程序相同的输出结果。



原文链接:http://www.cppblog.com/wanghaiguang/archive/2012/06/05/177644.html

猜你喜欢

转载自blog.csdn.net/KASH_SHADOW/article/details/55098793