实现一个栈类,类似STL中的栈

时间:2023-03-10 05:55:38
实现一个栈类,类似STL中的栈

1、思路讲解

stack集合类是一个简单的堆栈的实现。

这里有两个模板参数,T和size,T用于指定堆栈中的元素类型,my_size用于表示堆栈中项数的最大值。

类中添加方法isempty、isfull、push、pop。

2、涉及解说

  对于很久没用C++写代码的我,对于模板类很陌生了,所以首先简单介绍下模板类。

(1)用途:有那么一部分类,用途和方法是一样的,只是涉及的一些参数不同(如参数类型),这个时候引入了类模板来解决这个问题;有了类模板,我们在声明类的时候对于参数的不确定,我们先不给于具体的绑定,等到实例化的时候再指明具体的性质。

  例如函数模板的swap函数,有的想实现int型的两个变量值交换,有的想实现两个string型变量值的交换;有了函数模板,我们只需要写一个函数就可以解决不同需求:

 #include<iostream>
#include<string>
using namespace std; template<typename T>
void mySwap(T &a,T &b)
{
T temp;
temp = a;
a = b;
b = temp;
} int main()
{
//prepare parameter
int a1=,b1=;
string a2="Christal",b2="Carl";
//swap two int parameter
cout<<"a1= "<<a1<<" b1= "<<b1<<endl;
mySwap<int>(a1,b1);
cout<<"a1= "<<a1<<" b1= "<<b1<<endl;
//swap two string parameter
cout<<endl<<"a2= "<<a2<<" b2= "<<b2<<endl;
mySwap<string>(a2,b2);
cout<<"a2= "<<a2<<" b2= "<<b2<<endl; return ;
}

  输出结果:

实现一个栈类,类似STL中的栈

(2)用法:

 template<class 模板参数表>
class 类名
{
//类定义
};
int main()
{
类名<参数类型> 对象名;
}

  其中,template是类模板声明的关键字;模板参数可以只有一个,也可以有多个;参数可以是类型参数也可以是非类型参数;类型参数用关键字class或typename;非类型参数由一个普通参数构成,代表模板定义中的一个常量。

 template<class type,int width> class Hey;
//type为类型参数,width为非类型参数

(3)类模板的实例化

  type、width是形参,同类型的实参值被提供给形参;指定的每个不同类型的值都创建一个新类。

 template<class type,int width>
class Hey
{
private:
type str;
int maxwidth;
public:
Hey():maxwidth(width){}
};

  type被指定为string,width被指定为10,创建一个类;

1 Hey<string,> say1;

  type被指定为char,width被指定为1,创建一个类;

1 Hey<char,> say2;

3、思路实现

 #include<iostream>
#include<string>
using namespace std; template<class T,int my_size> //T:type , my_size:size
class myStack
{
private:
int top; //top pointer
T items[my_size]; //stack array
const int max_size; //array size
public:
myStack():max_size(my_size),top(-){}
bool isempty();
bool isfull();
void push(const T temp);
T pop();
};
template<class T,int my_size>
bool myStack<T,my_size>::isempty()
{
if(top == -)
return true;
else
return false;
}
template<class T,int my_size>
bool myStack<T,my_size>::isfull()
{
if(top == max_size-)
return true;
else
return false;
}
template<class T,int my_size>
void myStack<T,my_size>::push(const T temp)
{
if(!isfull())
{
items[++top] = temp;
}
}
template<class T,int my_size>
T myStack<T,my_size>::pop()
{
if(!isempty())
{
return items[top--];
}
} int main()
{
//prepare parameter
int i=;
string x;
string temp[] = {"Christal","Carl","Jerry","Belle","Sea","vinky","Rita","Nila"};
//initialize stack
myStack<string,> s;
//push someone
while(!s.isfull())
{
s.push(temp[i]);
cout<<"push one person"<<endl;
i++;
}
cout<<endl<<"stack is full"<<endl<<endl;
//pop someone
while(!s.isempty())
{
x = s.pop();
cout<<x<<" is pop"<<endl;
}
cout<<endl<<"stack is empty"<<endl; return ;
}

  输出检验:

实现一个栈类,类似STL中的栈

相关文章