STL Queue

STL Queue

FIFO
包含头文件<queue>
Interface of a Queue
定义

1
2
3
4
5
namespace std {
template < typename T,
typename Container = deque<T> >
class queue;
}

内部Container默认使用deque实现的。
可以使用其他提供front(), back(), push_back(), pop_front()的顺序容器,如list。
Internal Interface of a Queue

The Core Interface

  • push() inserts an element into the queue.
  • front() returns the next element in the queue (the element that was inserted first).
  • back() returns the last element in the queue (the element that was inserted last).
  • pop() removes an element from the queue.
  • size()/empty()

Example of Using Queues

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main()
{

queue<string> q;
// insert three elements into the queue
q.push("These ");
q.push("are ");
q.push("more than ");
// read and print two elements from the queue
cout << q.front();
q.pop();
cout << q.front();
q.pop();
// insert two new elements
q.push("four ");
q.push("words!");
// skip one element
q.pop();
// read and print two elements
cout << q.front();
q.pop();
cout << q.front() << endl;
q.pop();
// print number of elements in the queue
cout << "number of elements in the queue: " << q.size() << endl;
system("Pause");
}

[1] The C++ Standard Library 2nd Edition