stack in c++

stack在c++stl中作爲特殊容器存在,其實現多爲單純地把各項操作轉化爲內部容器的對應調用

下面是其簡單實現

頭文件

#ifndef _STACK_H
#define _STACK_H

#include<deque>
#include<exception>

template <typename T>
class Stack{
  protected:
  	std::deque<T> c;
  public:
  	class ReadEmptyStack:public std::exception{
  		public:
  			virtual const char* what() const throw(){
  				return "read empty stack";
			  }
	  };
	typename std::deque<T>::size_type size()const{
		return c.size();
	}
	bool empty()const{
	return c.empty();
	}
	void push(const T& elem){
		c.push_back(elem);
	}
	T pop(){
		if(c.empty())
		  throw ReadEmptyStack();
		T elem(c.back());
		c.pop_back();
		return elem; 
	}
	T& top(){
		if(c.empty())
		  throw ReadEmptyStack();
		return c.back();
	}
};
#endif
測試用例
#include "stack_c++.h"
#include<iostream>
using namespace std;

int main(){
	try{
		Stack<int>st;
		st.push(1);
		st.push(2);
		st.push(3);
		cout<<st.pop()<<' ';
		cout<<st.pop()<<' ';
		st.top()=77;
		st.push(4);
		st.push(5);
		st.pop();
		cout<<st.pop()<<' ';
		cout<<st.pop()<<endl;
		cout<<st.pop()<<endl; 
	}catch(const exception& e){
		cerr<<"EXCEPTION: "<<e.what()<<endl;
	}
}


發佈了52 篇原創文章 · 獲贊 15 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章