C++标准模板库STL介绍(一)

本文主要包括 stack、queue 常用函数的介绍(未完待续···)

stack

栈,STL 中实现的一个后进先出的容器。

push()

push(x) 将 x 入栈,时间复杂度为 O(1)

top()

top() 获得栈顶元素,时间复杂度为 O(1)

pop()

pop() 用以弹出栈顶元素,时间复杂度为 O(1)

empty()

empty() 可以检测 stack 内是否为空,返回 true 为空,返回 false 为非空,时间复杂度为 O(1)

size()

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

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
#include <stack>
using namespace std;
int main(){
stack<int> st; /* stack 的定义 */
if(st.empty() == true)
printf("Empty\n");
else
printf("Not Empty\n");
for(int i = 0; i <= 5; ++i)
st.push(i);
for(int i = 1; i <=3; ++i)
st.pop(); /* 连续三次将栈顶元素出栈 */
printf("%d\n", st.top());
if(st.empty() == true)
printf("Empty\n");
else
printf("Not Empty\n");
printf("%d\n", st.size());
return 0;
}

输出结果:
Empty
2
Not Empty
2

queue

队列,在 STL 中实现了一个先进先出的容器。

push()

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

front()、back()

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

pop()

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

empty()

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

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <queue>
using namespace std;
int main(){
queue<int> q; /* queue 的定义 */
if(q.empty() == true)
printf("Empty\n");
for(int i = 1; i <= 5; ++i)
q.push(i);
printf("%d %d\n", q.front(), q.back());

for(int i = 1; i <= 3; ++i)
q.pop(); /* 连续三次出队首元素 */
printf("%d\n", q.front());

if(q.empty() == false)
printf("Not Empty\n");
}

输出结果:
Empty
1 5
4
Not Empty

文章来源:

Author:Jiaqiang's Bolg
link:https://jiaqiangwu.top/2019/08/13/C 标准模板库STL介绍(一)/