IntSetArray implementation in c++
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 ve开发者_如何学Pythonry 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 and t
, what you are trying to insert, is 123.
The first statement in the insert
method is this:
for (int i=0;x[i]<t;i++)
This for loop increments i
while the i
th element of x
is less than t
. But the 0th element of x
is 300, which is not less than 123, so the loop never executes at all. Since in the constructor you only initialized the first element of x
, 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 x
where the value is greater or equal to t
, and then the inner loop shifts everything down and inserts t
. Then what you should be doing is this:
void insert(int t){
int i; // Declare this outside the first loop so that it
// remains accessible afterwords
for (i=0;x[i]<t;i++)
{
// Do nothing; the whole point is to increment i
}
// Now i contains the first index of x where x[i] >= t
// So now do the shift and insert:
if (x[i]==t)
return ;
for (int j=n;j>=i;j--)
x[j+1]=x[j];
x[i]=t;
n++;
}
A different, and potentially easier to understand, way to write this:
int i;
for (i=0;x[i]<t;i++)
{
// Do nothing; the whole point is to increment i
}
Is this:
int i = 0;
while (x[i] < t) ++i;
Why not use a std::set<int>
?
精彩评论