0

here is implementation IntSetList in c++

#include <iostream>
using namespace std;

class IntSetList{

private:
    int n;
    struct node{

        int val;
        node *next;
        node(int v,node *p){val=v;next=p;}
    };
    node *head,*sentinel;
    node *rinsert(node *p,int t){

        if (p->val<t){
            p->next=rinsert(p->next,t);


    }
        else   if (p->val>t){
            p=new node(t,p);
            n++;
        }
         return p;
            }



public:
    IntSetList(int maxelens,int maxval){
        sentinel=head=new node(maxval,0);
        n=0;
            }



    int size() { return n;}

    void insert(int t){  head=rinsert(head,t);}
    void report(int *v){

         int j=0;
         for (node *p=head;p!=sentinel;p=p->next)
             v[j++]=p->val;



    }




    void display (int *v){
         for (int i=0;i<sizeof(v)/sizeof(v[0]);i++){
             cout<<v[i];
         }





    }

};

int main(){



    IntSetList s(10,15);
    int v[10];
    s.insert(7);
    s.insert(2);
    s.insert(1);
    s.insert(11);
    s.insert(13);
    s.insert(14);
    s.insert(5);
    s.insert(6);
    s.insert(12);
    s.insert(9);
    s.report(v);

    s.display(v);






     return 0;
}

but it does not show me any output of course there is c++ standart library but i need to implement myself so i am making practises please help what is wrong?

  • You might want to tell us what you want/expect it to do. Right now, it *looks* a lot like a slower version of `std::set` (or maybe `std::multiset`). – Jerry Coffin Jul 25 '10 at 05:43

1 Answers1

1

No output at all? I suspect that it is outputting at least one number, since sizeof(v) is at least as big as sizeof(v[0]), but probably only just as big, since a pointer is the same size as an int on most 32-bit computers.

The sizeof(v)/sizeof(v[0]) trick only work on arrays, not pointers. A common trick to get around this is to declare the function as a template, thus:

template <int N>
void display (int (&v)[N])
{
     for (int i = 0; i < N; ++i)
     {
         cout << v[i];
     }
}

A more conventional solution is to pass the length explicitly:

void display (int *v, int n)
{
     for (int i = 0; i < n; ++i)
     {
         cout << v[i];
     }
}

A couple of points to note:

  1. This will mash all the numbers together because you haven't put any whitespace in between them.
  2. The display function doesn't have to be a member of IntSetList, since it doesn't interact with the class at all.

The simplest solution, BTW, is to not write the function at all:

std::copy(v, v + sizeof(v)/sizeof(v[0]), std::ostream_iterator<int>(std::cout));
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365