类数组插入函数

Class Array Insert Function

本文关键字:函数 插入 数组      更新时间:2023-10-16

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

#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?插入函数中的条件不是应该终止这两个条件吗?

这是因为您之后总是进入"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++;
}
}