#include <iostream> #include <string> #include <vector> using namespace std; //定义一个模板类 template <typename T> class Stack{ public: Stack(){}; //构造函数 ~Stack(){}; bool isEmpty() const; //判断堆栈是否为空 T peek(int pos) const; //查找指定位置元素 void push(T value); //往堆栈尾部中添加元素 void pop(); //删除最后一个元素 int getSize() const; //获取数据长度 void printStack() const; //打印堆栈 private: vector<T> val; //保存数据 }; //模板类实现 template<typename T> bool Stack<T>::isEmpty() const{ return val.empty(); } template<typename T> T Stack<T>::peek(int pos) const{ return val[pos]; } template<typename T> void Stack<T>::push(T value){ val.push_back(value); } template<typename T> void Stack<T>::pop(){ val.pop_back(); } template<typename T> int Stack<T>::getSize() const{ return val.size(); } template<typename T> void Stack<T>::printStack() const{ if(val.empty()){ cout << "Stack if empty" << endl; return; } for(auto &i : val) cout << i << " "; cout << endl; } int main(){ //Create a stack of int values Stack<int> intStack; for(int i = 0; i < 20; i++) intStack.push(i); intStack.pop(); intStack.printStack(); //Create a stack of strings Stack<string> stringStack; stringStack.push("Chicago"); stringStack.push("Denver"); stringStack.push("London"); stringStack.push("California"); cout << stringStack.peek(2) << endl; stringStack.printStack(); return 0; }
运行结果:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
London
Chicago Denver London California