stack的介绍使用及模拟实现
1、stack的介绍
1、stack是一种容器适配器,这种适配器的特点是后进先出
2、stack是作为容器适配器被实现的
3、stack的底层容器可以是任何标准的容器类模板或者一些其他特定的容器类,支持判空、返回栈顶、入栈,出栈的操作
4、默认使用deque作为stack的底层
2、stack的基本操作
函数说明 | 接口说明 |
---|---|
stack() | 构造空的栈 |
empty() | 检测stack是否为空 |
size() | 返回stack中元素的个数 |
top() | 返回栈顶元素的引用 |
push() | 将元素val压入stack中 |
pop() | 将stack中尾部的元素弹出 |
#include <iostream>
#include <stack>
using namespace std;
void TestStack1()
{
stack<int> s1;//构造s1
stack<int> s2(s1);//拷贝构造s2
}
void TestStack2()
{
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
cout << s.empty() << endl;
cout << s.size() << endl;
cout << s.top() << endl;
for (int i = 0; i < s.size(); i++)
{
cout << s.top() << endl;
s.pop();
}
}
int main()
{
TestStack1();
TestStack2();
system("pause");
return 0;
}
2、stack的模拟实现
stack.h
#include <iostream>
#include <deque>
using namespace std;
namespace gwp
{
template<class T, class Con = deque<T>>
class stack
{
public:
stack()
{
}
void push(const T& x)
{
m_c.push_back(x);
}
void pop()
{
m_c.pop_back();
}
T& top()
{
return m_c.back();
}
const T& top() const
{
return m_c.back();
}
size_t size()
{
return m_c.size();
}
bool empty()
{
return m_c.empty();
}
private:
Con m_c;
};
}
stack.cpp
#include <iostream>
#include "stack.h"
using namespace std;
int main()
{
gwp::stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
cout << s.size() << endl;
cout << s.empty() << endl;
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
system("pause");
return 0;
}