栈的vector实现

来源:互联网 发布:linux vi 全选复制 编辑:程序博客网 时间:2024/06/15 09:50
#ifndef STACK_ARRAY_H#define STACK_ARRAY_H#include <vector>#include <memory>using namespace std;template<typename Object>class Stack_Array{public:Stack_Array():theSize(0),data(make_shared<vector<Object>>()) {}Stack_Array(const Stack_Array &rhs):theSize(rhs.theSize),data(rhs.data) {}Stack_Array& operator=(const Stack_Array &rhs){if (this != &rhs){theSize = rhs.theSize;data = rhs.data;}return *this;}int size() const { return theSize; }bool empty() const { return theSize == 0; }Object &top() const{return data->back();}void push(const Object &x){data->push_back(x);++theSize;}void pop(){data->pop_back();}private:unsigned int theSize;shared_ptr<vector<Object>> data;};#endif

测试代码:

int main(){Stack_Array<int> s;for (int i = 0; i != 10; ++i)s.push(i);cout << s.size() << endl;cout << s.top() << endl;s.pop();cout << s.top() << endl;}

输出结果:


原创粉丝点击