stack的模拟实现
在STL中,stack的底层实现默认采用deque,且stack属于容器适配器
一共实现了stack的以下接口
push
pop
top
size
empty
#include<iostream>
#include<deque>
#include<list>
using namespace std;
template<class T, class Con = deque<T>>
class Stack
{
public:
void push(const T& x) {
_c.push_back(x);
}
void pop() {
_c.pop_back();
}
T& top() {
return _c.back();
}
const T& top()const {
return _c.back();
}
size_t size()const {
return _c.size();
}
bool empty()const {
return _c.empty();
}
private:
Con _c;
};
void test() {
Stack<int, deque<int>> st;
st.push(1);
st.push(2);
st.push(3);
st.push(4);
st.push(5);
cout << st.size() << endl;
while (!st.empty()) {
cout << st.top() << endl;
st.pop();
}
}
int main() {
test();
return 0;
}