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+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.