C++ queue隊列容器

queue是隊列容器,是一種“先進先出”的容器。
例如公共電話亭。必須有人出來,下一個才能進入。
如圖:在這裏插入圖片描述

默認情況下queue是利用deque容器實現的一種容器。

它只允許在隊列的前端(front)進行刪除操作,而在隊列的後端(back)進行插入操作。

使用queue需包含頭文件#include <queue>

以上筆記來自騰訊課堂騎牛學院!


定義

queue採用模板類實現,queue對象的默認構造形式:queue< T > q1;

queue<int> q1;
queue<double> q2;
queue<char> q3;

// queue定義時默認使用deque作爲他的存儲對象,
queue<int, deque<int>q1;
// 也可以修改list容器。
queue<int, list<int>> q4;



queue<int> q5 = q1;		// 拷貝構造
queue<int> q6;
q6 = q1;			// 賦值運算符重載重載
queue<int> q7(q1);	// 拷貝構造

注意:不能修改爲vector容器。


// 尾部插入
q1.push(1);

// 頭部刪除
q1.pop();

// 獲取隊首的值
q1.front();

// 獲取隊尾的值
q1.back();

// 獲取容器中的元素個數
q1.size();

// 判斷容器是否爲空
q1.empty();

// 交換容器的元素
q1.swap(q2);


注意:queue隊列容器沒有迭代器,所以,想要輸出裏面的所有值,唯有以下方法:

while (!q2.empty()) {			// 如果不爲空則繼續執行
	cout << q2.front() << " ";	// 輸出隊列頭部的值
	q2.pop();					// 隊列頭部出隊
}
cout << endl;

測試代碼:

#include <iostream>
#include <Windows.h>
#include <queue>
#include <list>

using namespace std;

// 定義
void test1(void) {
	queue<int> q1;
	queue<double> q2;
	queue<char> q3;

	// queue定義時默認使用deque作爲他的存儲對象,
	// 也可以修改list容器。注意:不能修改爲vector容器。
	queue<int, list<int>> q4;


	queue<int> q5 = q1;	
	queue<int> q6;
	q6 = q1;	// =重載
	queue<int> q7(q1);	// 拷貝構造
}

// 頭部刪除與尾部增加
void test2(void) {
	queue<int> q1;

	// 尾部插入
	q1.push(1);
	q1.push(2);
	q1.push(3);
	
	// 頭部刪除
	q1.pop();

	// 獲取隊首的值
	int front = q1.front();	

	// 獲取隊尾的值
	int back = q1.back();

	cout << "隊首:" << front << " 隊尾:" << back << endl;

	// 可以直接修改隊首和隊尾的值
	q1.front() = 111;
	q1.back() = 222;

	cout << "隊首:" << q1.front() << " 隊尾:" << q1.back() << endl;
}

// empty 與 size
void test3(void) {
	queue<int> q1;
	queue<int> q2;

	q1.push(1);
	q1.push(2);
	q1.push(3);

	// 獲取容器中的元素個數
	q1.size();

	// 判斷容器是否爲空
	q1.empty();

	if (!q1.empty()) {
		cout << "容器個數:" << q1.size() << endl;
	} else {
		cout << "容器爲空!" << endl;
	}

	// 交換容器的元素
	q1.swap(q2);


	while (!q2.empty()) {			// 如果不爲空則繼續執行
		cout << q2.front() << " ";	// 輸出隊列頭部的值
		q2.pop();					// 隊列頭部出隊
	}
	cout << endl;
}

int main(void) {
	//test1();

	//test2();

	test3();

	system("pause");
	return 0;
}

STL其他容器學習鏈接:

  1. C++ map 和 multimap 容器

  2. C++ set 和 multiset 容器

  3. C++ list容器

  4. C++ deque容器

  5. C++ vector容器

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章