头文件MyStack_deque.h
#pragma once #include <deque> #include <string> #include <stdexcept> //普通模板 template<typename T> class MyStack {}; //模板的特化 template<> class MyStack<std::string> { private: std::deque<std::string> elems;//容器 public: MyStack();//默认构造,必须有 void push(std::string const&);//入栈 void pop();//出栈 std::string top() const;//返回栈顶元素 bool empty() { return elems.empty(); }//返回栈是否为空 }; #define __MYSATCK_DEQUE__ #include "MyStack_deque.cpp"
实现头文件MyStack_deque.cpp
#ifdef __MYSATCK_DEQUE__ //默认构造 inline MyStack<std::string>::MyStack(){} //入栈 inline void MyStack<std::string>::push(std::string const& elem) { elems.push_back(elem); } //出栈 inline void MyStack<std::string>::pop() { if (elems.empty()) throw std::out_of_range("Stack<std::string>::pop(): empty stack"); elems.pop_back(); } //返回栈顶元素 inline std::string MyStack<std::string>::top() const { if (elems.empty()) throw std::out_of_range("Stack<std::string>::pop(): empty stack"); return elems.back(); } #endif // __MYSATCK_DEQUE__
测试main.cpp
#include <iostream> #include <string> #include "MyStack_deque.h" int main() { //特化之用deque实现stack的测试 { //创建别名 using StringStack = MyStack<std::string>;//c++11新特性,也可以用MyStack_vecotr里的那个typedef try { StringStack stringStack;//元素类型为string的栈 //使用string栈 stringStack.push("hello");//把"hello"入栈 std::cout << "stringStack top is " << stringStack.top() << std::endl;//返回栈顶元素 stringStack.pop();//出栈 stringStack.pop();//故意出空栈,看看会发生什么 } catch (std::exception const& ex) { std::cerr << "Exception: " << ex.what() << std::endl; return EXIT_FAILURE; } } }