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");
}
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");
}
相关文章推荐
- C++_模板举例_使用模板实现集合类(堆栈)
- C++ 模板应用举例_模板实现STL类(堆栈)
- 使用C++模板实现栈的求最小值功能
- C++使用模板实现数值型字符串类型间的转换
- 实现C++堆栈模板
- C++使用模板实现顺序表
- 使用C++模板技术实现类的动态注册和获取
- c++使用嵌套类实现堆栈
- C++ 使用模板实现单例模式
- C++ 使用模板实现的一个List
- Java集合系列(三)—— 使用LinkedList实现堆栈,队列
- 使用模板方法模式实现选择题答题 C++
- C/C++使用模板实现数据栈
- [设计模式]_[中级]_[模板方法C++例子实现举例]
- 使用C++实现AVL树模板
- 使用C++的类模板实现Stack类
- [设计模式]_[中级]_[模板方法C++例子实现举例]
- C++ 使用模板实现冒泡排序
- C++入门学习:类模板的使用(函数在类的内外实现的不同)
- 使用C++模板实现不需要IDL的RPC【二】