[计算机科学经

3 p27 template template typename t1 typename t2 class

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: <typename T> class Stack { private: std::vector<T> elems; public: void push(T const&); void pop(); T top() const; bool empty() const { return elems.empty(); } }; // 元素 // // // // push 元素 pop 元素 傳回最頂端元素 stack 是否為空 C++ Templates - The Complete Guide 22 3 Class Templates(類別模板) template <typename T> void Stack<T>::push (T const& elem) { elems.push_back(elem); // 追加(附於尾) } template <typename T> void Stack<T>::pop () { if (elems.empty()) { throw std::out_of_range("Stack<>::pop: empty stack"); } elems.pop_back(); // 移除最後㆒個元素 } template <typename T> T Stack<T>::top () const { if (elems.empty()) { throw std::out_of_range("Stack<>::top: empty stack"); } return elems.back(); // 傳回最後㆒個元素的拷貝 } 正如你所見,這個 class template 是以標準程式庫的 class template vector<> 為基礎實作出來的, 這樣我們就...
View Full Document

This note was uploaded on 08/25/2012 for the course EECS 101 taught by Professor Wre during the Fall '12 term at Beacon FL.

Ask a homework question - tutors are online