C++ queue用法
只能訪問queue
queue操作
- front():返回queue中第一個元素的引用。如果queue是常量,就返回一個常引用,如果queue為空,返回值是未定義的。
- back():返回queue中最后一個元素引用
- push(const T &obj):在queue的尾部添加一個元素的副本。
- pop():刪除queue中的第一個元素
- size():返回queue中元素的個數
- empty():如果queue中沒有元素返回true。
- emplace():用傳給emplace()的參數調用T的構造函數,在queue的尾部生成對象。
例子:
#include<Windows.h>
#include <iostream>
#include<queue>
#include<string>
#include<thread>
#include<mutex>
using namespace std;
::queue<int> q;
::mutex mutex1;
void fun1()
{
while (true)
{
lock_guard<mutex> guard(mutex1);
q.push(clock());//入隊列
std::this_thread::sleep_for(1ms);
}
}
void fun2()
{
while (true)
{
lock_guard<mutex> guard(mutex1);
if (!q.empty())//先判斷隊列是否有元素
{
cout << q.front() << endl;//獲取第一個元素的值
q.pop();//彈出第一個元素
}
std::this_thread::sleep_for(2ms);
}
}
int main()
{
thread th1(fun1);
thread th2(fun2);
th1.detach();
th2.detach();
int c = ::getchar();
}