我是靠谱客的博主 妩媚飞机,这篇文章主要介绍C++ STL 学习| queueC++ STL 学习| queue,现在分享给大家,希望可以做个参考。

C++ STL 学习| queue

queue

queue的定义

queue翻译为队列,在STL中主要实现一个先进先出的容器,使用queue需要添加头文件#include<queue>,并加上一句using namespace std;此外,queue可用来以邻接表的方式储存图。

单独定义一个queue

复制代码
1
2
queue<typename> name;

与之前的容器相同,typename可为任何基本类型,如int、double、char、结构体等,也可以是STL标准容器,如vector,set、queue等。

复制代码
1
2
3
4
5
queue<int> name; queue<double> name; queue<char> name; queue<node> name;
复制代码
1
2
queue<queue<int> > name;

queue容器内元素的访问

由于queue本身是一种先进先出的限制性数据结构,在STL中只能通过front()访问队首元素,通过back()访问队尾元素

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
#include<stdio.h> #include<queue> using namespace std; int main() { queue<int> q; for(int i = 1; i <= 5; i++) { q.push(i); } printf("%d %d", q.front(), q.back()); return 0; }

queue常用函数实例解析

(1)push()

push(x)将x进行入队,时间复杂度为O(1)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<stdio.h> #include<vector> using namespace std; int main() { queue<int> q; for(int i = 1; i <= 3; i++) { q.push(i); } for(int i = 0; i < q.size(); i++) { printf("%d ", q[i]); } return 0; }

(2)front()、back()

front()和back()可以分别获得队首元素和队尾元素,时间复杂度为O(1)

(3)pop()

pop()令队首元素出队,时间复杂度为O(1)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<stdio.h> #include<queue> using namespace std; int main() { queue<int> q; for(int i = 1; i <= 5; i++) { q.push(i); } for(int i = 1; i <= 3; i++) { q.pop(); } printf("%d", q.front()); return 0; }

(4)empty()

empty()用来检测queue是否为空,返回true则空,返回false则非空。时间复杂度为O(1)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
#include<stdio.h> #include<queue> using namespace std; int main() { queue<int> q; if(q.empty() == true) printf("Empty!n"); else printf("Not empty!n"); q.push(1); if(q.empty() == true) printf("Empty!n"); else printf("Not empty!n"); return 0; }

(5)size()

size()返回queue内元素个数,时间复杂度为O(1)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
#include<stdio.h> #include<queue> using namespace std; int main() { queue<int> q; for(int i = 1; i <= 5; i++) { q.push(i); } printf("%d", q.size()); return 0; }

**总结:**当需要实现广度优先搜索时,可以不用自己手动实现队列,而是用queue作为代替,以提高程序的准确性。且在使用front()和pop()函数前,必须使用empty()函数判断队列是否为空,否则可能因为队空而出现错误。

**延伸:**STL的容器中还有两种容器跟队列有关,分别是双端队列(deque)优先队列(priority_queue)前者是首尾皆可插入和删除的队列后者是使用堆实现的默认将当前队列最大元素置于队首的容器。

最后

以上就是妩媚飞机最近收集整理的关于C++ STL 学习| queueC++ STL 学习| queue的全部内容,更多相关C++内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部