队列是不同数据类型的集合,是数据结构的重要组成部分,按照特定的顺序插入和删除元素。在本教程中,我们将了解队列的基本操作。
数据结构中的队列是什么?
队列是一种线性数据结构,类似于现实生活中的队列。你们都曾在学校、帐单柜台或任何其他地方排队,第一个进入的人将第一个退出队列。同样,数据结构中的队列也遵循先进先出原则,定义了先进先出。与其余元素相比,首先插入队列的元素将首先终止。
队列有两个端点,并且对两端开放。
Front - 这是元素移出队列的末尾。
后 - 这是元素插入队列的末尾。

可以使用一维数组、指针、结构体和链表来实现。 C++库包含各种有助于管理队列的内置函数,其操作仅发生在前端和后端。
声明队列的语法
queue<data type> queue_name
示例
queue<int> q
queue<string> s
基本队列操作
C++ 中队列最有用的操作如下 -
pop() - 它删除队列的前面元素。 语法 -queue_name.pop();
push() -():用于在队列的开头或后端插入元素。 语法 -queue_name.push(data_value);
front() -():检查或返回队列前面的元素。 语法 -queue_name.front();
size() - 用于获取队列的大小。 语法 -queue_name.size();
empty() - 它检查队列是否为空。根据条件返回布尔值。 语法 -queue_name.empty();
push() 函数的代码。
#include <iostream>
#include<queue>
using namespace std;
int main() {
queue<int> q; //initializing queue
q.push(4); //inserting elements into the queue using push() method
q.push(5);
q.push(1);
cout<<"Elements of the Queue are: ";
while(!q.empty()) {
cout<<q.front()<<""; // printing 1st element of the queue
q.pop(); // removing elements from the queue
}
return 0;
}
输出
Elements of the queue are: 451
在上面的例子中,我们创建了一个队列q,并使用push()函数向其中插入元素,该函数将所有元素插入到后端。
使用empty()函数检查队列是否为空,如果不为空,队列将返回最前面的元素,使用pop()函数将从最前端删除队列元素。 p>
示例
#include <iostream>
#include<queue>
using namespace std;
int main() {
queue<int> q; //initializing queue
q.push(4); //inserting elements into the queue using push() method
q.push(5);
q.push(1);
cout<<"Elements of the Queue are: ";
while(!q.empty()) {
cout<<q.front()<<""; // printing 1st element of the queue
q.pop(); // removing elements from the queue
}
return 0;
}
输出
size of queue is : 451
队列的empty()函数示例。
#include <iostream>
#include<queue>
using namespace std;
int main() {
queue<string> q; //declaring string type of queue
q.push("cpp"); //inserting elements into the queue using push() method
q.push("Java");
q.push("C++");
if(q.empty()) //using empty() function to return the condition
cout<<"yes, Queue is empty";
else
cout<<"No, queue has elements";
return 0;
}
输出
.........................................................