一、stack 的介绍
stack 翻译为栈,在 STL 中主要则是实现了一个后进先出的容器。
二、stack 的定义
单独定义一个 stack:
stack<typename> name;
//这里的typename可以是任何基本类型,例如 int、double、char、结构体等,也可以是STL标准容器,例如vector、set、queue等。
三、stack 容器内元素的访问
由于栈(stack)本身就是一种后进先出的限制性数据结构,因此在 STL 中只能通过 top()来访问栈顶元素。
#include <stdio.h>
#include <stack>
using namespace std;
int main()
{
stack<int> st;
for (int i = 1; i <= 5; i++)
{
st.push(i); // push(i)用以把 i 压入栈,故此依次入栈 1 2 3 4 5
}
printf("%d\n", st.top());
return 0;
}
四、stack 常用函数实例解析
(1)push()
push(x) 将 x 进行入栈,时间复杂度为 O(1)。
(2)top()
top()获得栈顶元素,时间复杂度为 O(1)。
(3)pop()
pop()用以弹出栈顶元素,时间复杂度为 O(1)。
#include <stdio.h>
#include <stack>
using namespace std;
int main()
{
stack<int> st;
for (int i = 1; i <= 5; i++)
{
st.push(i); // push(i)用以把 i 压入栈,故此依次入栈 1 2 3 4 5
}
printf("%d\n", st.top());
st.pop();
printf("%d\n", st.top());
st.pop();
printf("%d\n", st.top());
return 0;
}
(4)empty()
empty() 检测 stack 是否为空,返回 true 则空,返回 false 则非空 。时间复杂度为 O(1)。
(5)size()
size() 返回 stack 中元素的个数,时间复杂度为 O(1)。
#include <stdio.h>
#include <stack>
using namespace std;
int main()
{
stack<int> st;
if (st.empty() == true)
{
printf("EMPTY! \n");
}
else
{
printf("NOT EMPTY! \n");
}
for (int i = 0; i < 6; i++)
{
st.push(i); //push(i) 用来将 i 压入队列,因此依次入队 0 1 2 3 4 5
}
if (st.empty() == true)
{
printf("EMPTY! \n");
}
else
{
printf("NOT EMPTY! \n");
}
printf("%d\n", st.size());
return 0;
}
五、stack 的常见用途
stack 用来模拟实现一些递归,防止程序对栈内存的限制而导致程序运行出错。
一般来说,程序的栈内存空间很小,对有些题目来说,如果用普通的函数来进行递归,一旦递归层数过深(不同机器不同,约几千到几万层),则会导致程序运行崩溃。如果用栈来模拟递归算法的实现,则可以避免这一方面的问题(不过这种应用出现较少)。
优先队列(priority_queue):使用堆实现的默认将当前队列最大元素置于队首的容器。