您的位置:首页 > 编程语言 > C语言/C++

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

2013-11-24 12:16 483 查看
初学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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  CC++ 模板