日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++超細致講解隊列queue的使用_C 語言

作者:panamera12 ? 更新時間: 2022-07-01 編程語言

queue介紹

只能訪問 queue<T> 容器適配器的第一個和最后一個元素。只能在容器的末尾添加新元素,只能從頭部移除元素。

許多程序都使用了 queue 容器。queue 容器可以用來表示超市的結賬隊列或服務器上等待執行的數據庫事務隊列。對于任何需要用 FIFO 準則處理的序列來說,使用 queue 容器適配器都是好的選擇。

調用#include< queue>即可使用隊列類

queue<Type,Container> (<數據類型,容器類型>)

初始化時必須要有數據類型,容器可省略,省略時則默認為deque類型

queue<int>q1;

queue<double>q2;

queue<char>q3;

//默認為用deque容器實現的queue;

queue<char, list<char>>q1;//用list容器實現的queue

queue<int, deque<int>>q2;//用deque容器實現的queue

queue 的生成方式和 stack 相同,下面展示如何創建一個保存字符串對象的

std::queue<std::string> words;

也可以使用拷貝構造函數:

std::queue<std::string> copy_words {words}; // A duplicate of words

stack<T>、queue<T> 這類適配器類都默認封裝了一個 deque<T> 容器,也可以通過指定第二個模板類型參數來使用其他類型的容器:

std::queue<std::string, std::list<std::string>>words;

底層容器必須提供這些操作:front()、back()、push_back()、pop_front()、empty() 和 size()。

注意:不能用vector容器初始化queue

因為queue轉換器要求容器支持front()、back()、push_back()及 pop_front(),說明queue的數據從容器后端入棧而從前端出棧。所以可以使用deque和list對queue初始化,而vector因其缺少pop_front(),不能用于queue。

queue常用函數

1.常用函數

  • push() 在隊尾插入一個元素
  • pop() 刪除隊列第一個元素
  • size() 返回隊列中元素個數
  • empty() 如果隊列空則返回true
  • front() 返回隊列中的第一個元素
  • back() 返回隊列中最后一個元素

2.函數運用示例

1:push()在隊尾插入一個元素

 queue <string> q;
    q.push("first");
    q.push("second");
    cout<<q.front()<<endl;

輸出 first

2:pop() 將隊列中最靠前位置的元素刪除,沒有返回值

queue <string> q;
	q.push("first");
	q.push("second");
	q.pop();
	cout<<q.front()<<endl;

輸出 second

因為 first 已經被pop()函數刪掉了

3:size() 返回隊列中元素個數

queue <string> q;

q.push("first");

q.push("second");

cout<<q.size()<<endl;

//輸出2,因為隊列中有兩個元素

4:empty() 如果隊列空則返回true

queue <string> q;
    cout<<q.empty()<<endl;
    q.push("first");
    q.push("second");
    cout<<q.empty()<<endl;

分別輸出1和0

最開始隊列為空,返回值為1(ture);

插入兩個元素后,隊列不為空,返回值為0(false);

5:front() 返回隊列中的第一個元素

queue <string> q;

q.push("first");

q.push("second");

cout<<q.front()<<endl;

q.pop();

cout<<q.front()<<endl;

第一行輸出first;

第二行輸出second,因為pop()已經將first刪除了

6:back() 返回隊列中最后一個元素

queue <string> q;

q.push("first");

q.push("second");

cout<<q.back()<<endl;

輸出最后一個元素second

原文鏈接:https://blog.csdn.net/wteruiycbqqvwt/article/details/124640835

欄目分類
最近更新