【问题标题】:Class Array Insert Function类数组插入函数
【发布时间】:2020-01-01 11:42:21
【问题描述】:

所以我在检查从给定数据结构书中学到的代码时出错。我发现了插入函数 导致错误。到目前为止,这是我的代码:

#include<iostream>
using namespace std;
class list
{
    int Myarray[10];
    int Mysize;

    public:
        list(void)
        {Mysize=0;}

    bool Empty()
    {
        return Mysize==0;
    }

    void Display()
    {
        for(int i=0;i<Mysize;i++)
        {
          cout<<Myarray[i]<<"";
        }
    }

    void Insert(int item,int pos)
    {
        if(Mysize==10)
        {
            cout<<"Full";

        }
        if(pos<0 ||pos >Mysize)
        {
            cout<<"Error";

        }

        for(int i=Mysize;i>pos;i--)
        {
            Myarray[i]=Myarray[i-1];
        }

            Myarray[pos]=item;
            Mysize++;



    }


    void Erase(int pos)
    {
        if(Mysize==0)
        {
            cout<<"Empty";
            return;
        }

        if(pos<0 || pos>= Mysize)
        {
            cerr<<"Error";
            return;
        }

        for(int i=pos;i<Mysize;i++)
        {
            Myarray[i]=Myarray[i+1];
        }
            Mysize--;

    }
};
    int main()
    {
        list X;

for (int i = 0; i < 9; i++)
{
cout<< "Inserting "<<i<<" at position "<<i/2<<endl;
X.Insert(i, i/2);


}
cout<<endl; 
X.Display();
cout <<"\nTry to insert at position -1" <<endl;
X.Insert(0, -1) ;
cout<<endl; 
X.Display();



cout << "\nTry to insert at position 10"<< endl;
X.Insert(0, 10);
cout<<endl; 
X.Display();
}

结果是:

Inserting 0 at position 0
Inserting 1 at position 0
Inserting 2 at position 1
Inserting 3 at position 1
Inserting 4 at position 2
Inserting 5 at position 2
Inserting 6 at position 3
Inserting 7 at position 3
Inserting 8 at position 4

135786420
Try to insert at position -1
Error
0135786420
Try to insert at position 10
Full
0

我不明白的是,既然我有条件:

if(pos<0 ||pos >Mysize)
{cout<<"Error";}

为什么将0插入-1位置时,应该是无效的也插入显示 结果呢?此外,当一个值被插入到第 10 个位置时,它会重置整个数组并变为 0?不是 Insert 函数中的条件应该终止这两个条件吗?

【问题讨论】:

  • 我建议你在Insert 函数中做一些rubber duck debugging。或者使用实际的调试器逐句逐句执行它。后者应该很明显问题是什么。
  • pos的类型改成std::uint32_t,那么pos&lt;0就不用管了

标签: c++ arrays class data-structures


【解决方案1】:

这是因为你总是在之后进行“for”循环。您需要使用:'if', 'else if' 然后将 'for' 放入 'else' 或在打印 'full' 或 'error' 后简单地返回。 例如:

void Insert(int item,int pos)
{
    if(Mysize==10)
    {
        cout<<"Full";
    }
    else if(pos<0 ||pos >Mysize)
    {
        cout<<"Error";
    }
    else {
        for(int i=Mysize;i>pos;i--)
        {
            Myarray[i]=Myarray[i-1];
        }
        Myarray[pos]=item;
        Mysize++;
    }
}

【讨论】:

    猜你喜欢
    • 2018-04-24
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多