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.