All about C plus plus algorithms!

Sunday 6 November 2016

Dynamic Array || Create a Class in C++ || C plus plus

Hi! In this post, I'll be creating a class called Dynamic Array with a number of utility functions.

What is a Dynamic Array?

A dynamic array is an array which is dynamically allocated. I'll be making int type array here. You can also make a char, double or float type class. It will have utility functions which double the size when we run out of storage plus functions like add element, remove element, etc. The advantage of this class is that while using it we wouldn't have to worry about resizing it or anything, we'll just make and object of class type and work with it.

If you have used String object before then you probably know already that how a class works. String is also a class with char data type.

Code for the Class

The private section of the class will contain 3 members:

class DynamicArray
{
 private:
          int* arr;  //our array
         int size;  //how many elements are there
         int cap;  //capacity i.e. how many elements can fit in the array

public:

       //utility functions here

}

Let's make the constructors first (write constructors in the public section). The default constructors, as mentioned previously, will have no parameters and it also has no return type.

DynamicArray()
{
     arr = nullptr; //since nothing in it at the time it is constructed hence point it to the null
     size = 0;          //nothing stored yet
     cap = 0;          //0 capacity
}

The parameterized constructor will have only one parameter i.e. the capacity in the beginning.

DynamicArray( int c )
{
    cap = c;
    size = 0;
    arr = new int[cap];  //making a dynamic array of capacity cap
}

What other functions do we require? Insert or Add Element, of course. The utility functions that are to be used by the user/public are to be made in public section. They are just like ordinary functions i.e. they have a return type.

PS: A point to remember is that while you are inside any function or constructor of the class, you can access its private members or private functions. Like I did in the constructors. But as soon as you go outside the class, you have access only to the public stuff.

Let's write code for the insert here. But there is a small point to consider, what if run out of capacity? In that case, we shall have to double the capacity. We can make a function for that as well which will double the capacity and since that function is only required by the insert function of this class (not required to the public), we shall make it private. So first, let's make a utility function called DoubleCap (double the capacity first)

void DoubleCap()
{
     int new_cap;
     if (cap == 0)
         new_cap = 1;

    else
   {
       new_cap = cap*2;   //doubling the capacity
       int* temp = new int[new_cap];    //made a temporary array since we need to shift data
       // if you don't know why make another temporary, please refer to  (Intro to Dynamic Allocation.)

        for (int i = 0; i < cap; i++)
                temp[i]  = arr [i];     //copying

         delete [] arr;
         arr = temp;
         cap = new_cap;
    }
    
}


void Insert(int d)   //d is that data that is to be inserted
{
    //there are two cases for insertion
   // first : when we have not overflowed the array i.e. capacity is available for insertion
  //second : when we have run out of capacity which requires doubling the capacity

      if (size < cap)
    {
        arr[size] = d;   //added the element at the next index e.g. when size was 0 (first insertion)
                               // we inserted at arr[0]
        size++;         // then increase the size by one
    }

   else                  //when size has surpassed the capacity
    {
        //calling the utility function
        DoubleCap();
        arr[size] = d;
        size++;
    }

}   //end of function

Now let's write the opposite of Insert i.e. Erase or Remove Element. I'll use another private utility function for it which will Half the Capacity when the size has dropped below half of the current capacity. It also will be a private function.

void HalfCap()
{
            int new_cap = cap/2;
            int* temp = new int[new_cap];
            
           for (int i = 0; i < size; i++)
                    temp[i] = arr[i];

         arr = temp;
         cap = new_cap;
}

void Erase()
{
     if (size < cap/2)
           HalfCap();
      
     size--;     //simply reduce the size, we don't delete it. 
     //by reducing size, we make it available for being over-written
}

We can make a number of other utility functions like Get Size which returns the size of the array in public.

int getSize()
{
     return size;
}

Or the Get Element which receives an index in parameter and returns whatever is stored at the index since the array arr is not accessible to the outside world and they can't access elements as arr[i]

int getElement( int i )
{
    return arr[i];
}

You can also try making the functions like Print Array.

In the end, we make the destructors. Destructors are made when the memory is being dynamically allocated in a class i.e. it has a dynamic element.

The prototype of the the destructor is just like that of the class. Except for ~ before the name which distinguishes it from the constructors. Plus, it has no parameters.

~DynamicArray()
{
    delete [ ] arr;
}

How to use the class?

First, you need to include it. Please refer to (Intro to Class.)
Using class and its utility functions is easy.
Make an object of class type.

How destructors and constructors are called?
The constructors are called automatically i.e. when you create the element. 
For instance,
   
DynamicArray obj1;    //the default constructors is called

int capacity = 20;
DynamicArray obj2(capacity);    //the parameterized constructor is called

DynamicArray obj3(25);            //parameterized constructor

I hope it has cleared the difference between calls for parameterized and default constructor. For parameterzed, you pass the parameters right when you create it. Writing as:

DynamicArray obj;
obj(25);                     //won't work!!

The destructor is called automatically when the program ends. Don't forget to make destructors for the class with dynamic allocation it can leads to the overflow in the Heap memory. Whatever you allocate on Dynamic Memory heap, must de-allocate it.

How to use utility functions?
Easy. Use the dot operator (.)
For example,

DynamicArray obj(10);
obj.Insert(55);
obj.Insert(44);
obj.PrintArray();
int size = obj.getSize(); 

Thank you for reading. Feel free to comment below. :)


Share:

0 comments:

Post a Comment

Popular Posts

Blog Archive

Copyright by progrithms.blogspot.com. All Rights Reserved.. Powered by Blogger.

Copyright © Programs and Algorithms | Powered by Blogger

Design by ThemePacific | Blogger Theme by NewBloggerThemes.com