Pages

Friday, 15 November 2013

Simple Class Template


Statement: A class template in C ++ which consists of an
                        array that can store elements of any
                        type (i.e.int, char, float etc)





template <class dataType>
class elementsList{
       dataType* _array;
       int size;


       int no_of_elements;

public:

       elementsList(){                   //Default Constructor

              size = 100;

              _array = new int[size];

              no_of_elements;

       }



       elementsList(int _size){          //Parametrized constructor

              size = _size;

              _array = new int[size];

              no_of_elements;
       }

       elementsList(const elementsList& obj){   //Copy Constructor
              size = obj.size;
              no_of_elements = obj.no_of_elements;
              for (int i = 0; i < no_of_elements; i++)
                     _array[i] = obj._array[i];
       }

       bool isEmpty() const{
              return (no_of_elements==0)
       }

       bool isFull() const{
              return (no_of_elements==size)
       }

       bool insert(const dataType& value){  //Inserts a value in the list
              if (isFull())
                     return false;
              _array[no_of_elements] = value;
              no_of_elements++;
       }

       bool remove(const dataType& value){   //Removes an element from the list
              int i;
              for (i = 0; i < no_of_elements;i++)
              if (_array[i] == value)
                     break;
              if (i == no_of_elements)          //If element is not present in the list
                     return false;
              for (i; i+1 < no_of_elements; i++)
                     _array[i] = _array[i + 1];
              return true;
       }

       bool search(const dataType& key, int& index){          //Searches a key in the list and if found, returns its index by reference to the main
              for (int i = 0; i < no_of_elements; i++)
              if (_array[i] == key){
                     index = i;
                     return true;
              }
              index = -1;             //If key not found
              return false;
       }
      
       void destroyList(){               //Destroys the list
              no_of_elements = 0;
       }

       void printList(){
              cout << "\t\tPRINTING LIST\n\n"
              for (int i = 0; i < no_of_elements; i++)
                     cout << _array[i] << endl;
       }

       ~elementsList(){           //Destructor
              delete _array;
              _array = nullptr;
       }
};



0 comments:

Post a Comment