So I am error checking the codes I learned from given data structure book.I found out the insert function is causing error.Here is my code so far:
#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();
}
The result is:
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
What I don't understand is that since I have the condition:
if(pos<0 ||pos >Mysize)
{cout<<"Error";}
Why is that when inserting 0 into -1 position which supposed to be invalid is also inserted as display in the result?Furthermore when a value is inserted into 10th position it resets the whole array and becomes 0?Isn't it the condition in the Insert function should have terminate both these conditions?
Insertfunction. Or use an actual debugger to step through it statement by statement. The latter should make it very obvious what the problem is.posto std::uint32_t, then you dont need to care aboutpos<0