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

C++_模板举例_使用模板实现集合类(堆栈)

2013-10-26 21:35 591 查看
[cpp]
view plaincopyprint?

//stack集合类是一个简单的堆栈的实现。   
//这里有两个模板参数,T和size,指定堆栈中的元素类型和堆栈中项数的最大值。
  
//push 和 pop成员函数添加和删除堆栈中的项,并在堆栈底部增加。
  
#include <iostream>   
#include <algorithm>
  
#include <string>   
using namespace std;  
template <class T,int size> //出错点
  
class stack  
{  
private:  
    T items[size];  
    int top;  
    const int MaxSize;  
public:  
    stack():MaxSize(size)  
    {  
        top=-1;//指向栈底   
    }  
    bool IsFull();  
    bool IsEmpty();  
    void push(const T item);  
    T pop();  
};  
  
template <class T,int size>  
bool stack<T,size>::IsFull()  
{  
    if(top==MaxSize-1)  
    {  
        return true;  
    }  
    else  
    {  
        return false;  
    }  
}  
  
template <class T,int size>  
bool stack<T,size>::IsEmpty()  
{  
    if (top==-1)  
    {  
          
        return true;  
    }  
    else  
    {  
        return false;  
    }  
}  
  
template <class T,int size>//出错点
  
void stack<T,size>::push(const T item)  
{  
    if (IsFull())  
    {  
        cout<<"stack is full"<<endl;  
        return;  
    }  
    else  
    {  
        items[++top]=item;  
    }  
}  
  
template <class T,int size>  
T stack<T,size>::pop()  
{  
    if (!IsEmpty())  
    {  
        return items[top--];  
    }  
    else  
    {  
        cout<<"栈空"<<endl;  
        return 0;  
    }  
}  
  
void main()  
{  
    //stack<string,5> s;//栈中存放字符串
  
    stack<int,5> s;   //栈中存放整型数据
  
    while(!s.IsFull())  
    {  
        //s.push("123");//字符串入栈
  
        s.push(1);//整型数据入栈   
    }  
    while(!s.IsEmpty())  
    {  
        cout<<s.pop()<<endl;  
    }  
    system("pause");  
}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: