c++ 模板学习笔记:用数组和类模板模拟通用栈(权哥)

初学c++模板类,此处拾人牙慧,用数组和类模板模拟通用栈

#include <iostream>
#include <typeinfo>
#include <string>
#include <cstring>
#include <exception>
using namespace std;
template <typename T=int,int len=10>
class stack
{
	T a[len];
	int cur;
public:
	stack():cur(0){}
	const char* element(){return typeid(T).name();}
	int max_size(){return len;}
	bool empty(){return cur==0;}
	bool full(){return cur==len;}
	int size(){return cur;}
	void push(const T& d)throw(const char*){
		if(full()) throw("full");
		a[cur++]=d;
	}
	T pop() throw(const char*){
		if(empty()) throw("empty");
		return a[--cur];
	}
	const T& top(){return a[cur-1];};
	void clear(){cur=0;}
};

template <int len>
class stack<const char*,len>
{
	string a[len];
	int cur;
public:
	stack():cur(0){}
	const char* element(){return "const char*";}
	int max_size(){return len;}
	bool empty(){return cur==0;}
	bool full(){return cur==len;}
	int size(){return cur;}
	void push(const char *d)throw(const char*){
		if(full()) throw("full");
		a[cur++]=d;
	}
	const char* pop() throw(const char*){
		if(empty()) throw("empty");
		return a[--cur].c_str();
	}
/*如果返回const char*& 会编译出错:
error: invalid initialization of non-const reference of type ‘const char*&’ 
from a temporary of type ‘const char*’.
如果返回const char* const& 编译不报错,会有warning: returning reference to temporary*/
	const char* const& top() throw(const char*){
		if(empty()) throw("empty");
			return a[cur-1].c_str();
	}
	void clear(){cur=0;}
};

int main()
{
	stack<int> si;
	si.push(1);	si.push(2);	si.push(3);	si.push(4);
	cout << "top:" << si.top() << endl;
	cout << "element type:" << si.element() << endl;
	cout << "max_size:" << si.max_size() << ',' << "size:" << si.size() << endl;
	while(!si.empty()) cout << si.pop() << ' ';
	cout << "\n===============================\n";
	stack<char,15> sc;
	sc.push('+');	sc.push('-');	sc.push('*');	sc.push('/');
	cout << "top:" << sc.top() << endl;
	cout << "element type:" << sc.element() << endl;
	cout << "max_size:" << sc.max_size() << ',' << "size:" << sc.size() << endl;
	while(!sc.empty()) cout << sc.pop() << ' ';
	cout << "\n===============================\n";
	
	stack<const char*> scp;
	char buf[20];
	while(1){
		cin >> buf;
		if(!strcmp(buf,"end")) break;
		scp.push(buf);
	}
	cout << "element type:" << scp.element() << endl;
	cout << "max_size:" << scp.max_size() << ',' << "size:" << scp.size() << endl;
	cout << "top:" << scp.top() << endl;
	while(!scp.empty()) cout << scp.pop() << ' ';
	cout << "\n===============================\n";
	
	return 0;		
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值