C++ STL 中的 queue::front() 和 queue::back()


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

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

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

什麼是 queue::front()?

queue::front() 是 C++ STL 中一個內建函式,它宣告在標頭檔案中。queue::front() 返回對插入到其關聯的佇列容器中的第一個元素的引用。換句話說,front() 直接引用佇列容器中最舊的元素。

如上圖所示,head 即 1 是第一個進入佇列的元素,tail 即 -4 是最後一個或最近進入佇列的元素。

語法

myqueue.front();

此函式不接受任何引數。

返回值

此函式返回對佇列容器中第一個插入的元素的引用。

示例

Input: queue<int> myqueue = {10, 20, 30, 40};
      myqueue.front();
Output:
      Front element of the queue = 10

示例

線上演示

#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue;
   Queue.push(10);
   Queue.push(20);
   Queue.push(30);
   Queue.push(40);
   Queue.push(40);
      cout<<"Element in front of a queue is: "<<Queue.front();
   return 0;
}

輸出

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

佇列首部的元素是:10

什麼是 queue::back()?

queue::back() 是 C++ STL 中一個內建函式,它宣告在標頭檔案中。queue::back() 返回對插入到其關聯的佇列容器中的最後一個元素的引用。換句話說,back() 直接引用佇列容器中最新的元素。

語法

myqueue.back();

此函式不接受任何引數。

返回值

此函式返回對佇列容器中最後插入的元素的引用。

示例

Input: queue<int> myqueue = {10, 20 30, 40};
      myqueue.back();
Output:
      Back element of the queue = 40

示例

線上演示

#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue;
   Queue.push(10);
   Queue.push(20);
   Queue.push(30);
   Queue.push(40);
   Queue.push(50);
      cout<<"Elements at the back of the queue is: "<<Queue.back();
   return 0;
}

輸出

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

Elements at the back of the queue is: 50

更新於:2020-03-06

2K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告