类数组插入函数
Class Array Insert Function
所以我正在错误地检查我从给定的数据结构书中学到的代码。我发现了插入功能 导致错误。这是我到目前为止的代码:
#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++;
}
}
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 当我尝试在 Main 中调用插入函数时,它不是取数字?
- 为 std::vector 编写自定义插入函数
- 类数组插入函数
- 无法在构造函数中执行设置元素插入
- 需要帮助将字符串插入函数
- 尝试使用 EvtSetChannelConfigProperty() 函数更新最大事件日志文件大小时插入的错误值
- 通过构造函数插入 std::map
- 在 C++ 中为特定哈希表创建插入函数
- sqlite3 c 函数:插入语句作为参数时未执行
- 编译器可以将静态模板函数插入
- SegFault将插入std :: vector的成员函数插入std :: vector
- 默认情况下构造函数插入数据后,我没有得到任何输出,但我不确定为什么不
- 如何将变量类型作为参数函数插入
- 插入迭代器与容器的成员函数插入器
- 将函数插入主要部分
- 递归函数插入二叉搜索树无法按根访问节点
- 使用自定义哈希函数插入到一个无序集合中
- 如何使用std库函数插入std::列表并保持顺序