C 中的按/POP堆栈类程序
Push/pop stack class program in C++?
我已经编写并修改了C 书中的示例代码,以推出/弹出数字从堆栈类中推出。这是我理解的基本问题。这是代码。
//stakarray.cpp
//a stack as a class
#include <iostream>
using namespace std;
class Stack
{
private:
enum { MAX = 10 };
//int MAX=10;
int st[MAX];
int top;
public:
Stack()
{ top=0; }
void push(int var)
{ st[++top]=var; } //increments stack, input var
int pop()
{ return st[top--]; } //returns var, decrements stack
void show(int var)
{ cout << st[var]<< endl; }
};
int main()
{
//some stack operations
int i;
Stack s1;
s1.push(11);
s1.push(22);
cout<<"1: "<<s1.pop()<<endl; //22
cout<<"2: "<<s1.pop()<<endl; //11
s1.push(33);
s1.push(44);
s1.push(55);
s1.push(66);
for (i=0; i<= 10 ; i++)
{
cout<< "s1[" << i << "]= ";
s1.show(i);
}
return 0;
}
该程序的输出给出
1: 22
2: 11
s1[0]= 2
s1[1]= 33
s1[2]= 44
s1[3]= 55
s1[4]= 66
s1[5]= 0
s1[6]= 0
s1[7]= 0
s1[8]= 4196896
s1[9]= 0
s1[10]= 4
为什么S1 [0] = 2,S1 [8] = 4196896,S1 [10] = 4?是否有任何方法可以从私有访问最大值,或者我必须将其定义在类中的其他位置(不用为全局变量或Main()的一部分)?
元素0永远不会使用,因为在推送中,您使用插入前( top)而不是插入后(top )。
您的堆栈一次最多有4个元素,因此索引4之后的所有元素都有未定义的内容(即S1 [5] ... S1 [10]中的随机垃圾)。
在您的代码中,在设置值之前,您用预注++top
递增了顶部。因此,顶部将转到1,然后您将设置s1[1]=33
。如果您切换到收入后top++
,则在设置s[0]=33
之后您的计数器变量top
将增加。
//stakarray.cpp
//a stack as a class
#include <iostream>
using namespace std;
class Stack
{
private:
enum { MAX = 10 };
//int MAX=10;
int st[MAX];
int top;
public:
Stack()
{ top=0; }
void push(int var)
{ st[top++]=var; } //increments stack, input var
int pop()
{ return st[top--]; } //returns var, decrements stack
void show(int var)
{ cout << st[var]<< endl; }
};
int main()
{
//some stack operations
int i;
Stack s1;
s1.push(11);
s1.push(22);
cout<<"1: "<<s1.pop()<<endl; //22
cout<<"2: "<<s1.pop()<<endl; //11
s1.push(33);
s1.push(44);
s1.push(55);
s1.push(66);
for (i=0; i<= 10 ; i++)
{
cout<< "s1[" << i << "]= ";
s1.show(i);
}
return 0;
}
相关文章:
- 为什么在堆栈和堆上创建变量会产生相同的程序集代码?
- 我的堆栈和库存清单程序的结构有什么问题?
- 堆栈粉碎终止程序
- 如何从 x64 程序集中的堆栈中获取参数?
- C++,在对象内分配多个数据时,堆栈分配是否更有效? 在下面的程序中,类A_Heap的效率会更低吗?
- 在给定程序中降低矢量数组实现堆栈的时间复杂度有哪些不同的可能方法?
- Haskell堆栈设置 - 无法识别CPP程序
- 如何制作硬编码堆栈,而不是硬编码并保持程序正常运行
- 使用 valgrind 的地块测量 c++ 应用程序的最大内存使用量(堆栈和堆)
- 当提供巨大的输入时,中止在堆栈操作程序中调用错误
- 如何在内联程序集中调用函数时保留堆栈
- 堆栈程序输入名称并重印在C 中
- 程序终止时堆栈损坏?
- 有没有办法避免在发生堆栈粉碎时终止程序
- 如何在应用程序开始时破坏堆栈
- 我无法获得由 Clang 构建的优化 NDK 应用程序的调用堆栈
- C++堆栈:程序未执行
- C++ 堆栈程序 指针问题的 Wsing 数组 新字符[len],其中 len 为 2 创建 16 个字符
- 在堆栈程序中实现一个计数器,用于计算对象移动的次数
- 试图写一个c++堆栈程序