如何在c++中使用数组打印堆栈
How to print a stack using arrays in c++
我已经在我的程序中添加了所有所需的功能-例如push, pop和print,但我无法在控制台屏幕上打印堆栈输出。我创建了三个独立的文件,包含类、函数和主文件。我想知道我在堆栈中插入的元素是否成功插入,因此我需要打印更新后的堆栈。
stack.h
#ifndef Stack_H
#define Stack_H
using namespace std;
class Stack{
private:
//int const capacity=50;
int stack[50];
int count;
int top;
int maxitem;
public: //this is where the functions go
Stack();//constructor
void Push(int data);
void Pop(int delData);
void PrintStack();
};
#endif
stack.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>
#include "Stack.h"
using namespace std;
Stack::Stack()
{
top=-1;
};
void Stack::Push(int data){
top++;
cin>>data;
stack[top]=data;
count++;
cout<<"inserted succefully :"<<data<<endl;
}
void Stack::Pop(int item)
{
if(top<0){
cout<<"stack is empty";
}
else{
item=stack[top];
top--;
cout<<"The deleted elememt is: "<<item<<endl;
}
}
void Stack::PrintStack()
{
if (top<0)
{
cout<<"Stack is empty ";
}
for(int i =top; i<0; i--)
{
cout<<"STACK IS "<<stack[i]<<" "<<endl;
}
}
main.cpp
#include <cstdlib>
#include <iostream>
#include <stack>
#include "Stack.h"
using namespace std;
int main()
{
Stack R;
int ele;
int data;
cout<<"enter the maximum elements in stack "<<endl;
cin>>ele;
cout<<endl<<"now enter the elements in stack "<<endl;
for(int data=0; data<ele; data++){
R.Push(data);
R.PrintStack();
}
R.Pop(item);
R.PrintStack();//stack after deletion of element
system("pause");
}
例如,可以这样定义函数
void PrintStack()
{
for ( int i = top; i >= 0; --i ) std::cout << stack[i] << ' ';
}
考虑函数Pop没有意义。至少应该声明为
void Pop(int &delData);
我想知道我在堆栈中插入的元素是否成功插入,因此我需要打印更新后的堆栈。
Stack Container是一个后进先出的容器适配器,只允许你直接访问back元素(也就是top)。当您编写自己的Stack
类时,请记住这一点。如果你想确保你的值被实际插入,实现一个top()
函数返回stack[top]
处的值。每个push()
后检查top()
*注意-你可以编写一个适配器来访问std::stack
的标准实现中的底层容器c
。
相关文章:
- 动态分配的聊天数组打印缺失的数据和空
- 对象数组打印空白字符串
- 数组打印"random"值时出现问题
- 数组打印出垃圾值
- 数组打印奇怪的字符,例如 ∟ @
- 测量我的随机数数组打印的时间始终显示为 0 秒
- 数组打印出错误的数字
- 从对象数组打印字符串对象
- 您好,如何防止此函数使用质数数组打印 1
- 如何从主内部的数组打印总计
- 如何将数组打印为矢量形式
- 有人能给我一些关于在C++中使用数组打印出丰富、完美和不足的数字的提示吗
- 为什么我的C++数组打印相同的值
- 如何阻止我的数组打印地址
- 将值输入到结构数组 + 打印输出
- C++11 为什么 cout 从布尔数组打印大整数
- 从字符串数组打印其中一个字符串时出现空指针赋值错误
- 将无符号字符数组打印为十六进制
- 缩短的数组打印错误的结果
- C++中的字符串数组:打印额外的字符