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 中一个内置函数,它声明在
如上图所示,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 中一个内置函数,它声明在
语法
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP