SeqStack(Template<class T>)实现
2017-10-12 14:05
239 查看
顺序表实现模板栈(第二次)
这是发过的一个版本的栈的链接
这次用模板再做了一遍
配有测试过的main函数,可以直接学习使用。
这是发过的一个版本的栈的链接
这次用模板再做了一遍
配有测试过的main函数,可以直接学习使用。
#include <iostream> using namespace std; template<class T> class SeqStack{ public: SeqStack(int sz = 50); ~SeqStack(){ delete[]element; }; bool push(const T& x); bool pop(); bool getTop(T& x)const; bool isEmpty()const; bool isFull()const; int getSize()const; void makeEmpty(); template<class U> friend ostream& operator<<(ostream& os, SeqStack<U> s); private: T* element; int maxsize, top; }; template<class T> SeqStack<T>::SeqStack(int sz) { if (sz <= 0){ element = NULL; } else { element = new T[sz]; } maxsize = sz; top = -1; } template<class T> bool SeqStack<T>::push(const T& x){ if (isFull()){ return false; } else { element[++top] = x; return true; } } template<class T> int SeqStack<T>::getSize()const { return top + 1; } template<class T> bool SeqStack<T>::pop(){ if (isEmpty()){ return false; } else{ top--; return true; } } template<class T> bool SeqStack<T>::getTop(T& x)const{ if (isEmpty()){ return false; } else { x = element[top]; return true; } } template<class T> void SeqStack<T>::makeEmpty(){ top = -1; } template<class T> bool SeqStack<T>::isFull()const{ return top >= maxsize - 1; } template<class T> bool SeqStack<T>::isEmpty()const{ return top == -1; } template<class U> ostream& operator<<(ostream &os, SeqStack<U> s){ os<< "maxsize = "<< s.maxsize<< " top = "<< s.top<< endl; for (int i = s.top; i >= 0; --i){ os << s.element[i]; if (i != 0) os << " -> "; } return os; } int main(){ SeqStack<int> s; for (int i = 0; i < 20; ++i) s.push(i* 12 - 1); cout << s<< endl; for (int i = 0; i < 10; ++i) s.pop(); cout << s<< endl; }
相关文章推荐
- 类模板 template<class T>
- [置顶] 从零开始学C++之对象语义与值语义、资源管理(RAII、资源所有权)、模拟实现auto_ptr<class>、实现Ptr_vector .
- [UE4]C++实现动态加载的问题:LoadClass<T>()和LoadObject<T>() 及 静态加载问题:ConstructorHelpers::FClassFinder()和FObjectFinder()
- template<class T>
- [UE4]C++实现动态加载的问题:LoadClass<T>()和LoadObject<T>()
- template<class T>(转)
- C++类模板 template <class T>
- 模板声明中template <typename T>和template <class T>
- C++中template<class T> && template <typename T>(模板区分)
- template<class T>函数模板
- C++类模板 template <class T>
- ibatis 返回list<String[]>----resultClass="hashMap" 可以实现
- C++ 模板template<class T>和template<typename T>有区别吗?
- 用模板template<typename T>实现int double等类型转string
- [置顶] 从零开始学C++之对象语义与值语义、资源管理(RAII、资源所有权)、模拟实现auto_ptr<class>、实现Ptr_vector
- 模板 使用中注意的问题 template<class T>
- 用模板template<typename T>实现int double等类型转string
- template <class T> T * funcNew(T x,int n)
- 如何实现具有层次结构的 TreeView <一> (WPF/TreeView/Style/Template)
- template<class T>函数模板