首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++函数模板如何写两个不同类型的栈

2012-03-23 
C++函数模板怎么写两个不同类型的栈typedef char ElemType//元素类型typedefstruct{ElemType *base//栈

C++函数模板怎么写两个不同类型的栈
typedef char ElemType;//元素类型

typedef struct 
{
ElemType *base;//栈底位置
ElemType *top;//栈顶指针
int stacksize;//当前分配的存储容量

}SqStack;

//构造一个空顺序栈S
void InitStack(SqStack &S)
{
S.base = (ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!S.base)
exit(0);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}

//判断栈是否为空
bool StackEmpty(SqStack S)
{
if(S.base == S.top)
return true;
else
return false;

}


//取栈顶元素
bool GetTop(SqStack S,ElemType &e)
{
if(StackEmpty(S))
return false;
else
e = *(S.top-1);
return true;
}

ElemType GetTop(SqStack S)
{
return *(S.top-1);
}


//入栈
void Push(SqStack &S,ElemType e)
{
if(S.top - S.base >=S.stacksize )
{
S.base = (ElemType*)realloc(S.base,(STACK_INIT_SIZE+STACKINCREMENT)*(sizeof(ElemType)));
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;

}


//出栈
bool Pop(SqStack &S,ElemType &e)
{
if(StackEmpty(S))
return false;
e = *--S.top;
return true;

}





我一个栈这么写的,但是我再程序中想定义两个栈,一个字符型,一个整型的,但是我还是想用写的这个,不想重写一个,怎么用函数模板,我不太了解,求指教。

[解决办法]
template <typename T>
class Stack
{
...
};
[解决办法]
template<typename T>
class stack{
T*base;
T*top;
int stacksize;
public:
// member function
....
};

热点排行