开发者

IntSet array implementation

i have following code for implement IntegerSet Class,idea is that when i insert element it should sort ,and then print it

#include <iostream>
using namespace std;
class IntSet{
public :
    int n,*x;
public:
    IntSet(int maxelms,int maxval){
        x=new int[1+maxelms];
        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 print(){
         for (int i=0;i<n;i++){

             cout<<x[i]<<"  ";
         }
    }
};
int main(){
    IntSet b(11,20);
    b.insert(0);
    b.insert(6);
    b.insert(3);
开发者_如何学Go    b.insert(7);
    b.insert(5);
    b.insert(11);
    b.insert(10);
    b.insert(18);
    b.insert(13);
    b.insert(16);
    b.print();

    return 0;
}

but problem is that when i run,it shows only press any key to continue,what is wrong?


Your insert code never enters the loop (since the first element in the vector is always larger than whatever has been been passed to the function) and returns without doing anything.

The code is a bit obscure. Look up insertion sort – this is what you need here.

Apart from that, your code leaks memory since the class doesn’t clear up its memory. Better use std::vector instead of manually managed memory.


Donno, just try to run:

 IntSet b(11,20);
    b.print();
    b.insert(0);
    b.print();
    b.insert(6);
    b.print();
    b.insert(3);
    b.print();
    b.insert(7);
    b.print();
    b.insert(5);
    b.print();
    b.insert(11);
    b.print();
    b.insert(10);
    b.print();
    b.insert(18);
    b.print();
    b.insert(13);
    b.print();
    b.insert(16);
    b.print();

and see what's happen...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜