C++顺序栈模板类实现之模板类友元函数实现

来源:互联网 发布:mysql like 优化 编辑:程序博客网 时间:2024/06/06 18:57
最近项目不是很紧张,想把常用的数据结构和算法整理整理写一写,一来加深一下基础,二来以后写一些算法的时候可以多关注算法本身,而对于基本数据

结构可以直接拿过来熟练的使用。希望自己做下去。。。

1.栈的基本接口

const int MAXSIZE = 100;template<class T>class Stack{public:virtual void Push(const T& x) = 0;virtual bool Pop(T& x) = 0;virtual bool GetTop(T& x)const = 0;virtual bool IsEmpty()const = 0;virtual bool IsFull()const = 0;virtual int  GetSize()const = 0;};

2.顺序栈实现

#include<iostream>#include"stack.h"using namespace std;const int STACKINC = 20;template<class T>class SeqStack;template<class T>ostream& operator<<(ostream& os, const SeqStack<T>& s);//友元函数声明template<class T>class SeqStack:public Stack<T>{public:SeqStack(int sz=50);~SeqStack(){delete[]elements;}virtual void Push(const T& x);virtual bool Pop(T& x);virtual bool GetTop(T& x)const;virtual bool IsEmpty()const{return (top == -1)?true:false;}virtual bool IsFull()const{return (top == MAXSIZE-1)?true:false;}virtual int GetSize()const{return top + 1;}void MakeEmpty(){top = -1;}friend ostream& operator<< <>(ostream& os, const SeqStack<T>& s);//模板友元函数private:T* elements;int top;int maxSize;bool ProcessOverflow();};template<class T>SeqStack<T>::SeqStack(int sz):top(-1),maxSize(sz){elements  = new T[maxSize];if(elements == NULL)cout << "SeqStack allocation failed" << endl;}template<class T>void SeqStack<T>::Push(const T& x){if(IsFull() == true)ProcessOverflow();elements[++top] = x;}template<class T>bool SeqStack<T>::Pop(T& x){if(IsEmpty() == true) return false;x = elements[top--];return true;}template<class T>bool SeqStack<T>::GetTop(T& x)const{if(IsEmpty() == true) return false;x = elements[top];return true;}template<class T>bool SeqStack<T>::ProcessOverflow(){maxSize = maxSize + STACKINC;T* newArray = new T[maxSize];if(newArray == NULL){cout << "memory allocation failed" << endl;return false;}for(int i = 0; i <= top; i++)newArray[i] = elements[i];delete []elements;elements = newArray;}template<class T>ostream& operator<< (ostream& os, const SeqStack<T>& s){os << "top = " << s.top << endl;for(int i = 0; i <= s.top; i++)os << i << " : " << s.elements[i] << endl;return os;}

3.测试程序

#include"seqstack.h"int main(){SeqStack<int> seqstackObj(20);seqstackObj.Push(1);seqstackObj.Push(2);seqstackObj.Push(3);seqstackObj.Push(4);seqstackObj.Push(5);int x;seqstackObj.Pop(x);seqstackObj.Pop(x);cout << seqstackObj;return true;}

注意上述模板类友元函数的声明语法格式。

原创粉丝点击