C++简单的栈模型示例

编程入门 行业动态 更新时间:2024-10-22 17:32:20

C++简单的栈模型<a href=https://www.elefans.com/category/jswz/34/1770116.html style=示例"/>

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++简单的栈模型示例

本文发布于:2023-12-03 08:26:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1653202.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:示例   模型   简单

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!