赞
踩
使用过C++ STL的人应该知道,STL中自带的queue队列数据结构,本身不提供清空队列元素的基本方法;在这里,给大家说说如何自己编写代码清空queue队列的元素。
代码如下:
- #include<bits/stdc++.h>
- using namespace std;
-
- int main() {
- queue<int> q;
- for(int i=1;i<=3;i++) {
- q.push(i);
- }
- cout << "当前队列的长度为:" << q.size() << endl;
- //清空队列
- while(!q.empty()) { //只要队列不为空
- q.pop(); //一直出队
- }
- cout << "当前队列的长度为:" << q.size() << endl;
- return 0;
- }

可以定义一个空队列nq,然后用这个空队列与原来已经有元素的队列q进行交换,那么原来的队列q就是空队列,注意:swap交换的是内容本身。代码如下:
- #include<bits/stdc++.h>
- using namespace std;
- void clear(queue<int> &t) {
- queue<int> empty;
- swap(empty,t);
- }
- int main() {
- queue<int> q;
- for(int i=1;i<=3;i++) {
- q.push(i);
- }
- cout << "当前队列的长度为:" << q.size() << endl;
- //清空队列
- clear(q);
- cout << "当前队列的长度为:" << q.size() << endl;
- return 0;
- }

此处使用C++中的引用数据类型,这里用视频讲解一下,在C++中什么是引用数据类型?
引用数据类型说明
为什么写这篇文章呢?
因为在做一道BFS题目的时候用到了队列清空这一知识点,想着这应该也是很多人的盲区,在信息学奥赛的代码编程中,应该要多注意细节,这样才能在现场竞赛中做到镇定自若。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。