l_stack.h

来自「数据结构大作业:miniStack类的设计」· C头文件 代码 · 共 92 行

H
92
字号
#ifndef VECTOR_BASED_STACK_CLASS
#define VECTOR_BASED_STACK_CLASS

#include "l_except.h"	// for underflowError exception
#include <vector>  // 利用vector来实现stack!!

using namespace std;

template <typename T>
class miniStack
{
	public:
		miniStack();
			// constructor. create an empty stack

		void push(const T& item);
			// push (insert) item onto the stack.
			// Postcondition: the stack has a new topmost element and
			// the stack size increases by 1

		void pop();
			// remove the item from the top of the stack.
			// Precondition: the stack is not empty.
			// if the stack is empty, the function throws
			// the underflowError exception
     
		T& top();
			// return a reference to the element on the top
			// of the stack.
			// Precondition: the stack is not empty.
			// if the stack is empty, the function throws
			// the underflowError exception
		const T& top() const;
			// constant version of top()

		bool empty() const;
			// determine whether the stack is empty

		int size() const;
			// return the number of elements in the stack

	private:
    	vector<T> stackVector;
			// a vector object maintains the stack items and size
};
 template <typename T>
 miniStack<T>::miniStack()
 {}

 template <typename T>
 void miniStack<T>::push(const T& item)
 {
      stackVector.push_back(item);
 }

 template <typename T>
 void miniStack<T>::pop()
 {
         if (empty()) // 检查是否为空
				throw underflowError("miniStack pop(): stack empty");
         stackVector.pop_back();
 }

 template <typename T>
 T& miniStack<T>::top()
 {
         if (empty())
				throw underflowError("miniStack top(): stack empty");
         return stackVector.back();
 }
   
 template <typename T>
 const T& miniStack<T>::top() const
 {
         if (empty())
                 throw underflowError("miniStack top(): stack empty");
         return stackVector.back();
 }
   
 template <typename T>
 bool miniStack<T>::empty() const
 {
         return stackVector.size()==0;
 }
 
 template <typename T>
 int miniStack<T>::size() const
 {
         return stackVector.size();
 }
#endif	

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?