模板类的实例—栈

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

创建模板类的方法:

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

调试普通类。

把普通类改为模板类;

相关推荐
嘴贱欠吻!1 小时前
Flutter鸿蒙开发指南(七):轮播图搜索框和导航栏
算法·flutter·图搜索算法
张祥6422889041 小时前
误差理论与测量平差基础笔记十
笔记·算法·机器学习
qq_192779872 小时前
C++模块化编程指南
开发语言·c++·算法
代码村新手2 小时前
C++-String
开发语言·c++
cici158743 小时前
大规模MIMO系统中Alamouti预编码的QPSK复用性能MATLAB仿真
算法·matlab·预编码算法
历程里程碑4 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
2501_940315265 小时前
航电oj:首字母变大写
开发语言·c++·算法
lhxcc_fly5 小时前
手撕简易版的智能指针
c++·智能指针实现
CodeByV5 小时前
【算法题】多源BFS
算法
TracyCoder1235 小时前
LeetCode Hot100(18/100)——160. 相交链表
算法·leetcode