示例"/>
C++简单的栈模型示例
前言
最近在学习C++,由于该语言是手动管理内存,所以要对内存池、栈、数组等相关模型要多多了解,下面是一个简单的栈模型。
// dome.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "tools.h"
#include <functional>
using namespace std;
#include <vector>template<class T> //类模板,泛型。
class zhan
{
public:T *arr; //栈数组指针int p_size; //栈大小【数组大小】int top; //栈顶值
public:zhan(int p_size):p_size(p_size),top(0) //初始化列表{this->arr = new int[p_size]; //申请p_size大小数组的内存。}~zhan() {delete[] this->arr; //释放内存this->arr = NULL;}bool isEmpty() //判断栈顶是否为0,0则是空{return this->top <= 0; }bool isFull() //判断栈顶是否大于等于p_size,大于等于则栈满了{return this->top >= this->p_size;}bool push(T num) //向栈插入数据,同时栈顶值++{if (this->top < this->p_size) {cout << "存入值:" << num << endl;this->arr[this->top] = num;this->top++;return true;}return false;}bool pop(T &item) //栈顶值--,同时向栈取出数据到item的引用。{if (this->top < 0){return false;}this->top--;item = this->arr[this->top];return true;}
};
int main()
{zhan<int> arr(3);arr.push(1); arr.push(2); arr.push(3);int item;while (arr.isEmpty() == false){arr.pop(item);cout << "取出的值:" << item << endl;}return 0;
}
结果
更多推荐
C++简单的栈模型示例
发布评论