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

可以使用一维数组、指针、结构体和链表来实现。 C++库包含各种有助于管理队列的内置函数,其操作仅发生在前端和后端。
声明队列的语法
queue queue_name
示例
queue qqueue 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 #includeusing namespace std;int main() { queue 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 #includeusing namespace std;int main() { queue 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 #includeusing namespace std;int main() { queue 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
结论
队列可以存储整数和字符串元素。在数据结构中,多了一个队列,称为优先队列,它对所有队列元素具有优先权。
希望本教程能够帮助您理解数据结构中队列的含义。
以上就是数据结构中队列的基本操作的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1445357.html
微信扫一扫
支付宝扫一扫