模板类的实例—栈

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;
}

创建模板类的方法:

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

调试普通类。

把普通类改为模板类;

相关推荐
Dovis(誓平步青云)9 分钟前
探索C++标准模板库(STL):String接口的底层实现(下篇)
开发语言·c++·stl·string
草莓熊Lotso42 分钟前
【数据结构初阶】--算法复杂度的深度解析
c语言·开发语言·数据结构·经验分享·笔记·其他·算法
KyollBM1 小时前
【CF】Day75——CF (Div. 2) B (数学 + 贪心) + CF 882 (Div. 2) C (01Trie | 区间最大异或和)
c语言·c++·算法
feiyangqingyun1 小时前
Qt/C++开发监控GB28181系统/取流协议/同时支持udp/tcp被动/tcp主动
c++·qt·udp·gb28181
CV点灯大师1 小时前
C++算法训练营 Day10 栈与队列(1)
c++·redis·算法
GGBondlctrl1 小时前
【leetcode】递归,回溯思想 + 巧妙解法-解决“N皇后”,以及“解数独”题目
算法·leetcode·n皇后·有效的数独·解数独·映射思想·数学思想
武子康2 小时前
大数据-276 Spark MLib - 基础介绍 机器学习算法 Bagging和Boosting区别 GBDT梯度提升树
大数据·人工智能·算法·机器学习·语言模型·spark-ml·boosting
武子康2 小时前
大数据-277 Spark MLib - 基础介绍 机器学习算法 Gradient Boosting GBDT算法原理 高效实现
大数据·人工智能·算法·机器学习·ai·spark-ml·boosting
成工小白2 小时前
【C++ 】智能指针:内存管理的 “自动导航仪”
开发语言·c++·智能指针