模板类的实例—栈

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

创建模板类的方法:

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

调试普通类。

把普通类改为模板类;

相关推荐
YuTaoShao14 分钟前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法三)DP 空间优化
算法·leetcode·职场和发展
茉莉玫瑰花茶19 分钟前
C++ 17 详细特性解析(5)
开发语言·c++·算法
cpp_250132 分钟前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_250138 分钟前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
uesowys1 小时前
Apache Spark算法开发指导-Factorization machines classifier
人工智能·算法
程序员老舅1 小时前
C++高并发精髓:无锁队列深度解析
linux·c++·内存管理·c/c++·原子操作·无锁队列
划破黑暗的第一缕曙光1 小时前
[C++]:2.类和对象(上)
c++·类和对象
季明洵1 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
shandianchengzi1 小时前
【小白向】错位排列|图文解释公考常见题目错位排列的递推式Dn=(n-1)(Dn-2+Dn-1)推导方式
笔记·算法·公考·递推·排列·考公
I_LPL1 小时前
day26 代码随想录算法训练营 回溯专题5
算法·回溯·hot100·求职面试·n皇后·解数独