i have trying to imlement IntSetArray in c++ it compiles fine but result is wrong first 300 is ok and other numbers are below zero something very strange numbers .e.g -8231313 something like this)
what is wrong? it is code
#include <iostream>
using namespace std;
int quantity=10;
class Set
{
private :
int n,*x;
public:
Set(int maxval){
x=new int[quantity+1];
n=0;
x[0]=maxval;
}
int size(){ return n;}
void insert(int t){
for (int i=0;x[i]<t;i++)
{
if (x[i]==t)
return ;
for (int j=n;j>=i;j--)
x[j+1]=x[j];
x[i]=t;
}
n++;
}
void display()
{
for (int i=0;i<n;i++){
cout<<x[i]<<" "<<"\n";
}
}
};
int main(){
Set s(300);
s.insert(123);
s.insert(45);
s.insert(89);
s.insert(50);
s.insert(13);
s.insert(19);
s.display();
return 0;
}
Think through what happens the first time you try to insert something.
x[0]contains 300 andt, what you are trying to insert, is 123.The first statement in the
insertmethod is this:This for loop increments
iwhile theith element ofxis less thant. But the 0th element ofxis 300, which is not less than 123, so the loop never executes at all. Since in the constructor you only initialized the first element ofx, the remainder have garbage values which are never changed.I think that you most likely don’t want the second loop to be inside the first loop anyway. What it seems that you are trying to do with the outer loop is find the first position in
xwhere the value is greater or equal tot, and then the inner loop shifts everything down and insertst. Then what you should be doing is this:A different, and potentially easier to understand, way to write this:
Is this: