久久ER99热精品一区二区-久久精品99国产精品日本-久久精品免费一区二区三区-久久综合九色综合欧美狠狠

博客專欄

EEPW首頁 > 博客 > C++隊列queue用法詳解

C++隊列queue用法詳解

發布人:電子禪石 時間:2024-03-21 來源:工程師 發布文章
一、定義

queue是一種容器轉換器模板,調用#include< queue>即可使用隊列類。

一、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

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

因為queue轉換器要求容器支持front()、back()、push_back()及 pop_front(),

說明queue的數據從容器后端入棧而從前端出棧。所以可以使用deque和list對queue初始化,

.而vector因其缺少pop_front(),不能用于queue。

二、queue常用函數1.常用函數
  1. push() 在隊尾插入一個元素

  2. pop() 刪除隊列第一個元素

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

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

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

  6. 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/KEPROM/article/details/109744379


*博客內容為網友個人發布,僅代表博主個人觀點,如有侵權請聯系工作人員刪除。



關鍵詞: queue

技術專區

關閉