STL库的stack容器
stack
- 栈,一个先进后出的容器。
- stack是一种操作受限制的线性表,只能通过top()来访问栈顶元素。
- 不支持 “<<” ,不能使用“<<”直接输出栈内所有元素,只能使用top()函数获取栈顶元素;
- 集合( Stack / Queue / Hashtable 都没有索引),即不支持遍历,只能通过while循环,通过top()和pop()来完成栈内元素的查询。
1、构造函数
- stack s; //stack采用模板类实现, stack对象的默认构造形式:
stack s1; // 空栈,默认构造函数
- stack(const stack &s); //拷贝构造函数
stack s2(s1); // 拷贝构造函数
stack s2=s1; // 拷贝构造函数
#include <iostream>
#include <stack>
using namespace std;
int main() {
//------------------1.构造函数 和 拷贝构造函数
stack<int> s; // 定义一个空栈
cout << s.empty() << endl; // 1
stack<int> s1;
s1.push(1);
s1.push(2);
s1.push(3);
stack<int>s2(s1);
stack<int>s3 = s1;
while (s2.empty() == 0) {
cout << s2.top() << " "; // 3 2 1
s2.pop();
}
while (s3.empty() == 0) {
cout << s3.top() << " "; // 3 2 1
s3.pop();
}
return 0;
}
2、增
2.1 push()
push(x):将x入栈,时间复杂度为O(1)
2.2 emplace()
emplace(x): 将x入栈
两者区别
对于emplace,C++标准库的简要说明就是构造和插入元素,emplace可以直接传入构造对象需要的元素,然后自己调用其构造函数!
大概可以理解为push能做的,emplace都能做。
push是得传入得对象先得造好,再复制过去插入;而emplace则可以自己拿到构造对象所需得元素构造出来,直接插入即可。
emplace相比于push省去了复制这步,即使用emplace这种操作会更节省内存。
3、删 pop()
pop():出栈顶元素。
4、改
4.1 swap()交换
int main() {
//------------------ swap()
stack<int> s;
s.emplace(9);
s.emplace(6);
s.emplace(15);
s.emplace(-3);
stack<int> s1;
s1.push(1);
s1.push(2);
s1.push(3);
s.swap(s1);
while (s1.empty() == 0) {
cout << s1.top() << " "; // -3 15 6 9
s1.pop();
}
cout << endl;
while (s.empty() == 0) {
cout << s.top() << " "; // 3 2 1
s.pop();
}
return 0;
}
5、查 top()
top():获取栈顶元素,时间复杂度为O(1)
stack不支持遍历,只能通过top函数来遍历栈;
#include <iostream>
#include <stack>
using namespace std;
int main() {
//------------------1. resize(n)将list的长度改为n
stack<int> s1;
s1.push(1);
s1.push(2);
s1.push(3);
// 不支持遍历
while (!s1.empty()) {
cout << s1.top() << " "; // 3 2 1
s1.pop(); // 删除栈顶元素
}
return 0;
}
6、判空 empty()
empty():判断栈是否为空。
7、大小 size()
size():获得栈元素个数