数据结构中队列的基本操作
队列是一种包含不同数据类型的集合,是数据结构的重要组成部分,遵循特定的顺序插入和删除元素。在本教程中,我们将了解队列的基本操作。
什么是数据结构中的队列?
队列是一种线性数据结构,类似于现实生活中的队列。大家在学校、收银台或其他任何地方都排过队,先进入队列的人先离开队列。类似地,数据结构中的队列也遵循FIFO原则,即先进先出。与其余元素相比,最先插入队列的元素将最先被移除。
队列有两个端点,并且两端都开放。
前端 − 元素从队列中移出的端点。
后端 − 元素插入队列的端点。
它可以使用一维数组、指针、结构体和链表来实现。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()函数将从前端删除队列元素。
示例
#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;
}
输出
No queue has elements
结论
队列可以存储整数和字符串元素。在数据结构中,还有一个称为优先队列的队列,它对所有队列元素具有优先级。
我希望本教程能帮助您理解数据结构中队列的含义。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP