C++ STL 中的 queue::push() 和 queue::pop()


在本文中,我們將討論 C++ STL 中 queue::push() 和 queue::pop() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的佇列?

佇列是在 C++ STL 中定義的一種簡單的序列或資料結構,它以 FIFO(先進先出)的方式進行資料的插入和刪除。佇列中的資料以連續的方式儲存。元素在佇列的末尾插入,從佇列的開頭刪除。在 C++ STL 中,已經有一個預定義的佇列模板,它以類似於佇列的方式插入和刪除資料。

什麼是 queue::push()?

queue::push() 是 C++ STL 中一個內建函式,它在 標頭檔案中宣告。queue::push() 用於將新元素推入或插入到佇列容器的末尾或後面。push() 接受一個引數,即我們要推入/插入到關聯佇列容器中的元素,此函式還會將容器的大小增加 1。

此函式進一步呼叫 push_back(),這有助於輕鬆地在佇列的後面插入元素。

語法

myqueue.push(type_t& value);

此函式接受一個引數,該引數的值為 type_t 型別,即佇列容器中元素的型別。

返回值

此函式不返回任何值。

示例

Input: queue<int> myqueue = {10, 20 30, 40};
      myqueue.push(23);
Output:
      Elements in the queue are= 10 20 30 40 23

示例

 線上演示

#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue;
   for(int i=0 ;i<=5 ;i++){
      Queue.push(i);
   }
      cout<<"Elements in queue are : ";
   while (!Queue.empty()){
      cout << ' ' << Queue.front();
      Queue.pop();
   }
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Elements in queue are : 0 1 2 3 4 5

什麼是 queue::pop()?

queue::pop() 是 C++ STL 中一個內建函式,它在 標頭檔案中宣告。queue::pop() 用於從佇列容器的開頭或起始位置推入或刪除現有元素。pop() 不接受任何引數,並從與該函式關聯的佇列的開頭刪除元素,並將佇列容器的大小減小 1。

語法

myqueue.pop();

此函式不接受任何引數。

返回值

此函式不返回任何值。

示例

Input: queue myqueue = {10, 20, 30, 40};
      myqueue.pop();
Output:
      Elements in the queue are= 20 30 40

示例

 線上演示

#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue;
   for(int i=0 ;i<=5 ;i++){
      Queue.push(i);
   }
   for(int i=0 ;i<5 ;i++){
      Queue.pop();
   }
   cout<<"Element left in queue is : ";
   while (!Queue.empty()){
      cout << ' ' << Queue.front();
      Queue.pop();
   }
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Element left in queue is : 5

更新於:2020年3月6日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.