只能访问 queue<T> 容器适配器的第一个和最后一个元素。只能在容器的末尾添加新元素,只能从头部移除元素。std::queue: 模板类queue定义在<queue>头文件中。队列(Queue)是一个容器适配器(Container adaptor)类型,被特别设计用来运行于FIFO(First-in first-out)场景,在该场景中,只能从容器一端添加(Insert)元素,而在另一端提取(Extract)元素。只能从容器”后面”压进(Push)元素,从容器”前面”提取(Pop)元素。用来实现队列的底层容器必须满足顺序容器的所有必要条件。
queue 和 stack 有一些成员函数相似,但在一些情况下,工作方式有些不同:
- front():返回 queue 中第一个元素的引用。如果 queue 是常量,就返回一个常引用;如果 queue 为空,返回值是未定义的。
- back():返回 queue 中最后一个元素的引用。如果 queue 是常量,就返回一个常引用;如果 queue 为空,返回值是未定义的。
- push(const T& obj):在 queue 的尾部添加一个元素的副本。这是通过调用底层容器的成员函数 push_back() 来完成的。
- push(T&& obj):以移动的方式在 queue 的尾部添加元素。这是通过调用底层容器的具有右值引用参数的成员函数 push_back() 来完成的。
- pop():删除 queue 中的第一个元素。
- size():返回 queue 中元素的个数。
- empty():如果 queue 中没有元素的话,返回 true。
- emplace():用传给 emplace() 的参数调用 T 的构造函数,在 queue 的尾部生成对象。
- swap(queue<T> &other_q):将当前 queue 中的元素和参数 queue 中的元素交换。它们需要包含相同类型的元素。也可以调用全局函数模板 swap() 来完成同样的操作。
1、queue使用例程:
#include <cstdlib>
#include <iostream>
#include <queue>
using namespace std;
int main()
{
int e,n,m;
queue<int> q1;
for(int i=0;i<10;i++)
q1.push(i);
if(q1.empty())
cout<<"queue is empty.\n";
n=q1.size();
cout<<n<<endl;
m=q1.back();
cout<<m<<endl;
for(int j=0;j<n;j++)
{
e=q1.front();
cout<<e<<" ";
q1.pop();
}
cout<<endl;
if(q1.empty())
cout<<"queue is empty.\n";
return 0;
}
运行结果:
10
9
0 1 2 3 4 5 6 7 8 9
queue is empty.
{ // std::queue::emplace: C++11, Construct and insert element.
// Adds a new element at the end of the queue, after its current last element.
// The element is constructed in-place, i.e. no copy or move operations are performed.
// queue::push: inserts element at the end , queue::emplace: constructs element in-place at the end
// queue::pop: removes the first element
std::queue<std::string> myqueue;
myqueue.emplace("First sentence");
myqueue.emplace("Second sentence");
std::cout << "myqueue contains:\n";
while (!myqueue.empty()) {
std::cout << myqueue.front() << '\n';
myqueue.pop();
}
2、queue在多线程中的使用:
多线程通信经常使用消息队列queue。当一个线程频繁接收到消息,而已处理这个消息,需要耗费一点时间,处理消息阻塞当前线程,导致无法接到到新的消息,造成异常。因此额外开一个新的线程,此新线程只管处理消息,当前线程只管接收消息,接收后当前函数退出,处理其他任务,即可避免阻塞线程了。实现系统的稳定。在处理为了避免数据冲突,需要用到锁和条件锁(std::mutex)。