Define a class called Set that stores integers in a dynamica

Define a class called Set that stores integers in a dynamically allocated array of integers. class Set {public: void add(int n); bool contains(int n) const; int get_size() const; _____. private: int* elements int* size;};In asset, the order of elements does not matter, and every element can occur at most once. Supply the add, contains and get_size member functions and the bid three memory management function: Copy constructor Assignment operator Destructor

Solution

#define INCREMENT 32

/* We set a default value INCREMENT to dynamically increase the set when it exceeds a size of multiple values of INCREMENT.

For example, if size gets 64, new array will be created with size of 64+32 to accomodate new elements. See expand_set() function to know how it is done.

class Set{
   private:
       int* elements;
       int size;
//size variable need not be a pointer as we have to use it only to store an integer.
   public:
       Set(){
           elements=new int[INCREMENT];
           size=0;
       }
       Set(Set &set){
           elements=set.elements;
           size=set.size;
       }
       int get_size() const{
           return size;
       }

       bool contains(int n) const{ //Checks is a number is present in a set or not
           bool contains=false;
           for(int i=0;i<size;i++)
               if(elements[i]==n){
                   contains=true;
                   break;
               }
           return contains;
       }
       void expand_set(){ //Increases the length of dynamic array. See description at the start of this program
           int* newArray;
           int newLength=size+INCREMENT;
           newArray=new int[newLength];
           for(int i=0;i<size;i++)
               newArray[i]=elements[i];
           delete [] elements;
           elements=newArray;
       }
       void add(int n){
           if(contains(n))   return; // If number already exists, nothing hapens.
           if(size==(sizeof(elements)/sizeof(int)))   expand_set(); // is array is full, set needs to expand
           elements[size]=n;
           size++;
       }
       void operator=(Set &set) { //Operator overloading
           elements=set.elements;
           size=set.size;
       }
       ~Set(){ // Destructor used to delete all numbers in elements before freeing up the elements pointer itself.
           delete [] elements;
       }
};

 Define a class called Set that stores integers in a dynamically allocated array of integers. class Set {public: void add(int n); bool contains(int n) const; in
 Define a class called Set that stores integers in a dynamically allocated array of integers. class Set {public: void add(int n); bool contains(int n) const; in

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site