模板类的实例—栈

cpp 复制代码
#include<iostream>

using namespace std;

typedef int Datatype;

class Stack
{
private:
	Datatype* items;//栈数组
	int stacksize;//栈的实际大小
	int top;//栈顶指针
public:
	//构造函数:1)分配栈数组内存,2)把栈顶指针初始化为0;
	Stack(int size) :stacksize(size), top(0) {
		items = new Datatype [stacksize];
	}
	~Stack() {
		delete [] items;
		items = nullptr;
	}
	bool isempty()const {
		if (top == 0)return true;
		return false;
	}
	bool isfull()const {
		if (top == stacksize)return true;
		return false;
	}
	bool push(const Datatype& item) {
		//元素入栈;
		if (top < stacksize) {
			items[top++] = item; 
			return true;
		}
		return false;
	}
	bool pop(Datatype &item){
		if (top > 0) { item = items[--top]; return true; }
		return false;
	}
};
int main()
{
	Stack ss(5);

	//元素入栈;
	ss.push(1); ss.push(2); ss.push(3); ss.push(4); ss.push(5);
	//元素chu栈;
	Datatype item;
	while (ss.isempty() == false) {
		ss.pop(item);
		cout << "item = " << item << endl;
	}
	return 0;
}

接下来我们把这个普通类改为模板类;

cpp 复制代码
#include<iostream>

using namespace std;

template <class Datatype>
class Stack
{
private:
	Datatype* items;//栈数组
	int stacksize;//栈的实际大小
	int top;//栈顶指针
public:
	//构造函数:1)分配栈数组内存,2)把栈顶指针初始化为0;
	Stack(int size) :stacksize(size), top(0) {
		items = new Datatype [stacksize];
	}
	~Stack() {
		delete [] items;
		items = nullptr;
	}
	bool isempty()const {
		if (top == 0)return true;
		return false;
	}
	bool isfull()const {
		if (top == stacksize)return true;
		return false;
	}
	bool push(const Datatype& item) {
		//元素入栈;
		if (top < stacksize) {
			items[top++] = item; 
			return true;
		}
		return false;
	}
	bool pop(Datatype &item){
		if (top > 0) { item = items[--top]; return true; }
		return false;
	}
};
int main()
{
	Stack<int>ss(5);

	//元素入栈;
	ss.push(1); ss.push(2); ss.push(3); ss.push(4); ss.push(5);
	//元素chu栈;
	int item;
	while (ss.isempty() == false) {
		ss.pop(item);
		cout << "item = " << item << endl;
	}
	return 0;
}

创建模板类的方法:

先写一个普通类,用具体的数据类型。

调试普通类。

把普通类改为模板类;

相关推荐
luj_176832 分钟前
星火科技助力边远地区防病攻坚
c语言·开发语言·c++·经验分享·算法
zmzb01031 小时前
C++课后习题训练记录Day175
开发语言·c++
啦啦啦啦啦zzzz2 小时前
工具:动态类工厂和用配置文件存储属性
c++·设计模式·工具·动态工厂
脱胎换骨-军哥2 小时前
C++ 代码规范与格式化指南
开发语言·c++·代码规范
木木子222 小时前
# 鸿蒙 ArkTS 实战:秒表 Stopwatch(示例 5)
数据结构·华为·list·harmonyos
geats人山人海3 小时前
数据结构第六章c语言 树的存储下二叉树的概念和存储
c语言·数据结构·算法
漂流瓶jz4 小时前
UVA-12627 奇怪的气球膨胀 题解答案代码 算法竞赛入门经典第二版
算法·图论·递归·aoapc·算法竞赛入门经典·uva·12627
迷途之人不知返4 小时前
lambda表达式
c++
jarvisuni4 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
@三十一Y4 小时前
C++:红黑树的实现
开发语言·c++