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

最近项目不是很紧张,想把常用的数据结构和算法整理整理写一写,一来加深一下基础,二来以后写一些算法的时候可以多关注算法本身,而对于基本数据

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

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;
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值