【发布时间】:2021-03-29 09:23:37
【问题描述】:
这个类是一个堆栈,我试图让用户调用与堆栈相关的函数。但是,似乎没有进行任何更改,因为在调用显示函数时,我的整个堆栈都被零填充了。这是在将值压入堆栈之后。
#include <iostream>
using namespace std;
class Stack {
public:
int array[5];
int top;
Stack() {
top = -1;
for (int i = 0; i < 5; ++i) {
array[i] = 0;
}
}
bool isEmpty() {
if (top == -1) {
return true;
}
return false; }
bool isFull() {
if (top == 4) {
return true;
}
return false;
}
void push(int val) {
if (isFull()) {
cout <<"stack overflow" << endl;
}
else {
top++;
array[top] == val;
}
}
int pop() {
if (isEmpty()) {
cout << "stack underflow" << endl;
}
else {
int val = array[top];
array[top] = 0;
top--;
return val;
}
}
int count() {
return(top + 1);
}
int peek(int pos) {
if (isEmpty()) {
cout << "stack underflow";
return 0;
}
else {
return array[pos];
}
}
void change(int pos, int val) {
array[pos] = val;
}
void display() {
for (int i = 4; i >= 0; --i) {
cout << array[i];
}
}
};
int main() {
Stack stack;
int option, position, value;
do
{
cout << "What operation do you want to perform? Select Option number. Enter 0 to exit." << endl;
cout << "1. Push" << endl;
cout << "2. Pop" << endl;
cout << "3. isEmpty()"<< endl;
cout << "4. isFull()"<< endl;
cout << "5. peek()"<< endl;
cout << "6. count()"<< endl;
cout << "7. change()"<< endl;
cout << "8. display()"<< endl;
cout << "9. Clear Screen"<< endl<< endl;
cin >> option;
switch(option) {
case 1:
cout << "Enter item to push onto stack: " << endl;
cin>>value;
stack.push(value);
break;
case 2:
cout << "Popping from stack: " << stack.pop() << endl;
break;
case 3:
if (stack.isEmpty()) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
break;
case 4:
if (stack.isFull()) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
break;
case 5:
cout << "Enter position to peek" << endl;
cin >> position;
cout << stack.peek(position) << endl;
break;
case 6:
cout << stack.count() << endl;
break;
case 7:
cout << "Enter position followed by value: " << endl;
cin >> position >> value;
cout << "Position changed" << endl;
break;
case 8:
stack.display();
break;
case 9:
system("cls");
break;
}
}
while (option != 0);
return 0;
}
例如,用户会按 1 来调用 push() 并推送一些输入值。然后,他们输入 8 来调用 display,它应该在堆栈中显示输入值,但打印 00000
【问题讨论】:
-
打开你的编译器警告,或者阅读编译器给你的警告。你有几个错误。比如
pop检测到栈是空的,你会返回什么? -
“例如,用户会按下 [...]”——这表明你周围有干扰,可能会妨碍你的调试。忘记拥有用户。不要让用户输入干扰您的测试,您的minimal reproducible example。如果您想调用
push(),请调用push()。为您的调试创建一个程序副本,从该副本中删除 I/O,并简单地列出重现您的问题所需的函数和数据。也许将您的主要功能简化为int main() { Stack stack; stack.push(2); stack.display(); }。 -
即使您修复了
==错误,该程序仍然存在错误。如果用户从一开始就选择2,您的程序会遇到未定义的行为,因为如果堆栈为空,int pop()函数不会返回值。当它应该返回值时不返回值是未定义的行为。未定义的行为意味着程序可以崩溃,而不是崩溃,导致内存损坏,或者似乎“工作”。当堆栈为空时,您需要重做pop函数才能真正正常工作。
标签: c++ data-structures stack