队列是不同数据类型的集合,是数据结构的重要组成部分,按照特定的顺序插入和删除元素。在本教程中,我们将了解队列的基本操作。
数据结构中的队列是什么?队列是一种线性数据结构,类似于现实生活中的队列。你们都曾在学校、帐单柜台或任何其他地方排队,第一个进入的人将第一个退出队列。同样,数据结构中的队列也遵循先进先出原则,定义了先进先出。与其余元素相比,首先插入队列的元素将首先终止。
队列有两个端点,并且对两端开放。
front - 这是元素移出队列的末尾。
后 - 这是元素插入队列的末尾。
可以使用一维数组、指针、结构体和链表来实现。 c++库包含各种有助于管理队列的内置函数,其操作仅发生在前端和后端。
声明队列的语法queue<data type> queue_name
示例queue<int> qqueue<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
结论队列可以存储整数和字符串元素。在数据结构中,多了一个队列,称为优先队列,它对所有队列元素具有优先权。
希望本教程能够帮助您理解数据结构中队列的含义。
以上就是数据结构中队列的基本操作的详细内容。