【发布时间】: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<0就不用管了
标签: c++ arrays class data-structures