c++類模板實現堆棧

#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>

using namespace std;

template <class T>
class Stack { 
	private: 
		vector<T> elems;     // 元素 

	public: 
		void push(T const&);  // 入棧
		void pop();               // 出棧
		T top() const;            // 返回棧頂元素
		bool empty() const{       // 若是爲空則返回真。
			return elems.empty(); 
		} 
}; 

template <class T>
void Stack<T>::push (T const& elem) 
{ 
	// 追加傳入元素的副本
	elems.push_back(elem);    
} 

template <class T>
void Stack<T>::pop () 
{ 
	if (elems.empty()) { 
		throw out_of_range("Stack<>::pop(): empty stack"); 
	}
	// 刪除最後一個元素
	elems.pop_back();         
} 

template <class T>
T Stack<T>::top () const 
{ 
	if (elems.empty()) { 
		throw out_of_range("Stack<>::top(): empty stack"); 
	}
	// 返回最後一個元素的副本 
	return elems.back();      
} 

int main() 
{ 
	try { 
		Stack<int>         intStack;  // int 類型的棧 
		Stack<string> stringStack;    // string 類型的棧 

		// 操做 int 類型的棧 
		intStack.push(7); 
		cout << intStack.top() <<endl; 

		// 操做 string 類型的棧 
		stringStack.push("hello"); 
		cout << stringStack.top() << std::endl; 
		stringStack.pop(); 
		stringStack.pop(); 
	} 
	catch (exception const& ex) { 
		cerr << "Exception: " << ex.what() <<endl; 
		return -1;
	} 
}

運行結果:ios

$ ./a.out 
7
hello
Exception: Stack<>::pop(): empty stack
相關文章
相關標籤/搜索