【问题标题】:Why does popping off my stack return garbage instead of the initial variables?为什么弹出我的堆栈返回垃圾而不是初始变量?
【发布时间】:2019-03-02 22:36:44
【问题描述】:

当我运行我的程序时,它会将数字完美地推入数组。但是当它弹出它们,然后打印它们时,我得到了垃圾号码。问题是否与我的主要功能有关? 或者我没有在我的 Stack 类中正确初始化我的数组?起初我的构造函数有一些问题,但经过一些调整后似乎可以正常工作。

关于为什么我在运行我的脚本后收到垃圾号码,有什么突出的吗?

#include<iostream>
#include<cstdlib>
#ifndef MYSTACK_H
#define MYSTACK_H

#include<iostream>
#include<new>
using namespace std;


class MyStack
{
private:
    int *list;
    int top;
    int max;
public:
    MyStack(int m)
    {
        int max = m;
        list = new int[max];
        int top = -1;
    }
    ~MyStack()
    {
        delete[] list;
    }
    int push(int);
    int pop();
    int peek(int &a) const;
};

int MyStack::push(int a)
{
    if (top < max - 1)
    {
        top = top + 1;
        list[top] = a;
        return 0;
    }
    return -1;
}

int MyStack::pop()
{
    if (top > -1)
    {
        top = top - 1;
        return 0;
    }
    return -1;
}

int MyStack::peek(int &a) const
{
    if (top > -1)
    {
        return(list[top]);
        return 0;
    }
    return -1;
}

#endif

int main()
{
    MyStack m(5);
    for (int i = 0; i < 6; i++)
    {
        int x = 1 + rand() % 100;
        cout << x << "\t";
        m.push(x);
    }
    cout << "\n";
    for (int i = 0; i < 6; i++)
    {
        int x;
        m.peek(x);
        cout << x << "\t";
        m.pop();
    }
    cout << "\n";
    system("pause>nul");
}

【问题讨论】:

  • 阅读how to debug small programs。编译所有警告和调试信息 (g++ -Wall -Wextra -g)。顺便说一句,您的 list 名称令人困惑。最好使用 arr 或 tab ... 因为它不是 list

标签: c++ arrays stack


【解决方案1】:

调用MyStack的构造函数后没有设置top和max,你是在创建局部变量,成员不受影响:

int max = m; // local 
list = new int[max];
int top = -1; // local

改成

max = m;
list = new int[max];
top = -1;

【讨论】:

    【解决方案2】:

    参数a 从未在您的peek() 函数中使用:

    int MyStack::peek(int &a) const
    {
        if (top > -1)
        {
            return(list[top]); // you return the value instead of assigning it to "a"
            return 0; // unreachable by the way
        }
        return -1;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 2022-07-28
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      相关资源
      最近更新 更多