All about C plus plus algorithms!

Monday, 24 July 2017

What is Template in C++ || Type casting in C++



What's template? 

You have probably seen me using it in some classes that I posted earlier, for instance Stack Class. So what is the purpose of template? Well, templates allow us to use a class or object for different datatypes using type casting. For instance, the Stack class I made earlier can be used for char, int, double, float, string or any other class/object. 

For instance, I can use it for Int

myStack  <int> stackOne;

Or for Char

myStack  <char> stackTwo;

Or for String

myStack  <string> stackThree;

Or maybe for a struct

struct Student{

string RollNum;
string Name;
float cgpa;

}

myStack  <Student> stackFour;


In some way, it allows my Stack class to become universal.. or I should say not strictly limited to any data type.

How to use Template?

template <typename T>

This is the syntax to declare it. You can use any name in place of that T that I have used e.g.

template <typename myType>

If you are going to use it in any function or method, just declare it above that method. If there are several methods 一 I am not talking about functions within a class 一 declare it above each method.
For example,

template <typename A>

A Sum(A variable1, A variable2)  //Note that I have used A in place of datatype in return type and variables
{
      A answer = variable1 + variable2;
      return answer;
}


Now if you have another function below it, you will have to declare it again above that function.
Similarly, if you want it in a struct, you will declare it above that struct.
Same goes for the class, if you use it in a class, declare it above the class however the point to remember is that you will then not need to declare it again and again for each function in the class rather once declared outside is enough.

template <typename T>
class myStack
{
Vector  <T>  st;

public:
      T top()
     {
int s = st.getSize() - 1;
T ret = st[s];
return ret;
     }


     T getAt(int i)
    {
return st[i];
    }

}


That'll be all for today. Thank you for reading! ^^









Share:

Saturday, 22 July 2017

Stack Class in C++ || Your Own Stack

What is a Stack?

Stack is a static memory in the life cycle of a program. This memory region stores variables and references (pointers). The main feature to consider here is that stack memory works in LIFO order, that is, Last In First Out. So basically it has two functions of Push (pushing elements into the stack) and Pop (Pop out the last element in the stack). Also there is another function Top which lets you know which element is placed on the last filled slot. 

My own Stack Class

This class will have functions as Push, Pop, Top as well as some other utility functions like GetAt(int index) which tell that what element is placed on the index. And other functions like Size( ), Print( ) Empty( ) and Invert( ). 

To make this class, I have used Vector class that I made. To see it's code and explanation please view Vector Class and Iterator for it. 

template <typename T>
class myStack
{
Vector <T> st;

public:

       //utility functions and constructors here

}


This class is has small and easy code, which I believe needs no explaining. So I'll just share the code. 

#pragma once

#pragma once
#include <iostream>
#include "vector.h"
using namespace std;

template <typename T>
class myStack
{
Vector <T> st;

public:

void push(const T & obj)
{
st.push_back(obj);
}

void pop()
{
st.pop_back();
}

T top()
{
int s = st.getSize() - 1;
T ret = st[s];
return ret;
}

int size()
{
return st.getSize();
}

bool empty()     //returns true if stack is empty
{
if (st.getSize()== 0)
return true;

return false;
}

void invert()
{
int i = 0;
int s = st.getSize();
Vector <T> temp;
for (i = s-1; i >= 0; i--)
{
temp.push_back(st[i]);
}
st = temp;
}

T getAt(int i)
{
return st[i];
}

void print()
{
for (int j = 0; j < st.getSize(); j++)
{
cout << st[j];
}
}

};

Links for Code files





Thank you for reading. ^^
Share:

Monday, 17 July 2017

Linked String in C++ || PART 2 || C++ Class

As we have already discussed in the previous post about linked lists and how they work. Please view Linked String in C++ || PART 1 || C++ Class to see that post.


I have written the code for Singly linked list for characters. To assist creating nodes, I have made a function called CreateNode( ) inside the private of this class. This function creates a new node and returns the address of it. I have not made it public because the public users need not to make new nodes.

struct Node
{
char c;
Node* next;
};

class LinkedString
{
private:


Node* head, *tail;
int size;

Node* CreateNode(char d)
{
Node* temp = new Node;
temp->next = nullptr;
temp->c = d;
return temp;  //address of the created node
}

}

In the public, I have first made constructors.

LinkedString()   //default constructor
{
head = tail = nullptr;
size = 0;

}

LinkedString(const string & str)   //takes string as input and stores in the linked list
{
char c;
int n = str.size();

int i = 0;
while ( i < n)
{
c = str.at(i);

addCharAtEnd(c);

i++;
}
}

LinkedString(const LinkedString & obj)   //copy constructor
{

LinkedString lnk;

Node* holder = obj.head;
// size = 0;
if (holder != nullptr)
{
while (holder->next != nullptr)
{

lnk.addCharAtEnd(holder->c);  //the helping function made in private
holder = holder->next;
}

head = lnk.head;
tail = lnk.tail;
size = lnk.size;
}

}

As you can see I have used a function addCharAtEnd() in the copy constructor that inserts new node at the end of the list and makes the tail point to it. Its code will go into the private section of the class.


void  addCharAtEnd(char ch)
{
if (size == 0)
{
size++;
head = tail = CreateNode(ch);

}
else
{
tail->next = CreateNode(ch);
tail = tail->next;

size++;
}
}

Now I can't go explaining all the functions that I have made; some private, some public. So I will share the code only.

Here is the link to the drive folder containing the Header file which has the code for the class and a sample main file the run tests on those functions.

Source files for Linked List



Thank you for reading! ^^ And if you have any questions or confusions regarding the code, comment below. :)

Share:

Linked String in C++ || PART 1 || C++ Class


What is a Linked String?

Linked String is a sort of array but it differs from array as it has nodes and each nodes points to the next element. A linked string can be both, Singly-Pointed (points to the node next to it) and Doubly-Pointed (points to the previous and next node). Unlike array, the elements in the linked string are not stored consecutively, rather nodes maybe placed at different addresses in the memory. 
In an array, the elements are stored consecutively i.e. they are placed in consecutive memory address e.g. we have an array [1, 2, 3, 4], now the first element 1 一 let's assume 一 is stored at address 205 then undoubtedly the next element 2 will be stored on address 206, similarly 3 on 207 and 4 on 208. 

On the other hand, if we have a linked list that contains [1, 2, 3, 4], the elements may not be at consecutive address spaces. For instance, element 1 maybe stored at address 125 while element 2 at address 20, element 3 at address 750 and element 4 at address 342.

Now, how do we make it possible to keep track of which nodes come after the other, which is the first or the last? Because for sure, when we print, it prints in the sequence we inserted i.e.  1, 2, 3, 4. This is done through Nodes. 

What is a Node?

A node is a struct which contains the data and a pointer. Think of it like a box having two objects within it. The data is an elements of Data Type like int, char, double, string or anything else. While the pointer is to the next node so that we know which node comes after the current one. (In case of Singly-linked list, there is only one pointer : next, but in Doubly-linked list, there are 2 pointers : next and previous) The struct's code will be:

Template <typename T>
struct Node
{
T data;
Node* next;   //remember! The type of the pointer is Node as it points to a Node: Next node!
};

But we also need to have pointers to the first and last node; Head and Tail nodes respectively. These pointers are private members of our Linked List class. I will illustrate here with a singly linked list class for characters. 

class LinkedList
{
private:

Node* head, *tail;   
int size;   //currently number of nodes/elements in the list

}


Let's take previous example where we have a singly linked list that contains [1,2,3,4,5]. 


  • A Box depicts a Node
  • The text in Orange shows the data within the node
  • The Blue box inside node box shows the Pointer of type node and the purple colored text inside it shows the address of the next pointer saved in it
  • On the top of each box, the address in dark Blue shows the address on which that node is stored

Now in the image, you can see, that the head is also a node that contains address of the first node i.e. at 245 containing element 1. And then each node contains the data (the element of type char in this case) and the pointer of type node* that points (shows in green color) to the next node i.e. contains the address of the next node. The last node containing 5 has no node next to it so we set its next pointer to Null. And then we make our tail pointer point to the last node i.e. the one containing element 5. 

In the next post, I will share the code for this class plus some additional functions. Stay tuned! 😊




Share:

Thursday, 13 July 2017

Iterator Class || Example with Vector Class




What is a vector class?

Vector class is a 1D dynamic array that allows infinite entries. 

class Vector{

//private by default

T* arr;
int size;  //current number of elements
int cap;  //capacity

Public:

   //other functions here
}

The vector class has functions like Push and Pop to insert and remove elements, respectively.

void push_back(const T & obj)
{
if (size < cap)
arr[size++] = obj;

else
{
int ncap = cap * 2;
T* temp = new T[ncap];
for (int i = 0; i < cap; i++)
temp[i] = arr[i];

temp[cap] = obj;

delete [] arr;

arr = temp;
size++;
cap = ncap;
}
}

void pop_back()
{
size--;

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

delete[] arr;
arr = temp;
cap = cap / 2;
}


}

These two functions go into the public section of the vector class. There are some other functions as well that I have included in my vector class.

Vector()   //default constructor
{
cap = 256;       //using 256 capacity by default
arr = new T[cap];
size = 0;
}

Vector (int capacity)   //parameterized constructor
{
arr = new T[capacity];
cap = capacity;
size = 0;
}

void reallocate(int capacity)    //reallocation function
{
delete[] arr;
arr = nullptr;

arr = new T[capacity];
cap = capacity;
size = 0;
}

Vector(const Vector <T> &  obj)    //copy constructor
{

arr = new T[obj.cap];
cap = obj.cap;

for (int i = 0; i < obj.size; i++)
{
arr[i] = obj.arr[i];
}
size = obj.size;
}

const Vector<T> & operator = (const Vector <T> & obj)   //assignment operator overload
{
if (arr != nullptr)
delete[] arr;

arr = new T[obj.cap];
cap = obj.cap;

for (int i = 0; i < obj.size; i++)
{
arr[i] = obj.arr[i];
}
size = obj.size;


return obj;
}


void insert (iterator & position, const T & value)
{
int index = 0;
for (Vector <int> ::iterator itr = begin(); itr != position; ++itr)
{
index++;
}

for (int i = size; i > index; i--)
{
arr[i] = arr[i-1];
}

//inserted
arr[index] = value;
size++;

if (size >= cap)
{
int ncap = cap * 2;
T* temp = new T[ncap];
for (int i = 0; i <= cap; i++)
temp[i] = arr[i];

arr = temp;
cap = ncap;
}
}

void erase (iterator & position)
{
int index = 0;
for (Vector <int> ::iterator itr = begin(); itr != position; ++itr)
{
index++;
}
for (int i = index; i < size-1; i++)
{
arr[i] = arr[i + 1]; 
}

size--;

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

arr = temp;
cap = cap / 2;
}

}

What is an Iterator class?

Sometimes, we don't want to give public access to the class's private objects e.g. T* arr here through [ ] operator. In that case, we make another class within a class that provides us indirect access to that pointer/private object. The iterator for this vector class will look something like this:

class iterator {
protected:

T* ptr;
int i;     //index

Public:

   //other functions here

}

This class is in the public section of the Vector class.
I have also  made some other function that assist using iterator.

iterator (T* aptr, int ind)
{
ptr = aptr;
i = ind;
}
void operator ++ ()
{
i++; //go to next index

}

const iterator  & operator = (const iterator & obj)
{
if (arr != nullptr)
delete[] arr;

arr = new T[obj.cap];
cap = capacity;

for (int i = 0; i < obj.size; i++)
{
arr[i] = obj.arr[i];
}
size = obj.size;

return obj;
}


bool operator != (iterator & itr)
{
if (i != itr.i)
return true;

return false;

}

T & operator * ()
{
return ptr[i];
}

All of this goes in public section of the iterator class.
Now in the private section of the Vector class (after ending the iterator class), add these two functions.

iterator begin()
{
iterator itr(arr, 0);
return itr;
}

iterator end()
{
iterator itr(arr, size);
return itr;
}

The BEGIN function has return type Iterator. This function initializes the iterator (for whom this function is called) to the first index of the arr (arr is the dynamic array inside Vector class). Similarly, the END function has also the return type Iterator.  This function initializes the iterator (for whom this function is called) to the last index of the arr (arr is the dynamic array inside Vector class).

To illustrate more, let's see how we use the iterator class in our code/main.

Let's make a vector class object and use iterator to go through it.

Vector <int> v;       //using 256 by default capacity
                                 // int type
int s = 1;
for (int i = 0; i < 10; i++)
{
v.push_back(s++);    //inserting values through push back function
}

Now let's make an iterator to be used in a for loop that displays the elements of the vector on the screen.

for ( Vector <int> ::iterator itr = v.begin() ; itr != v.end(); ++itr )
{
cout << *itr << " ";
}

cout << endl;

As you can see, we define an Iterator, named itr, using Vector <int> ::iterator itr and then we initialize it to the start of the vector using the BEGIN function in the vector as Vector <int> ::iterator itr = v.begin(). Similarly, we check that whether itr has reached the end of the vector using != operator and END function. And we move to the next index using ++ operator of the Iterator class. 

Other than this, we can also insert or replace using iterator. 

Vector <int> :: iterator itr = v.begin();
for (;*itr != 6; ++itr);
v.insert( itr , -1);


That's all for today. :)

Thank you for reading.  😊😎







Share:

Friday, 25 November 2016

String class in C++ || C plus plus

Hi guys! 😊 We have already made the Dynamic Array class for the integers (See Dynamic Array Class for Int) but now let's make Dynamic Array class for the characters. Luckily, there's a ready-made class called String in C++ that works as Dynamic array for chars. It is available in <string> library.
However, if you want to make your own string class (probably for fun but most probably for it is an assignment 😜) then I'll show you how to do it.



Pre-Requisites:

  • Familiar with Dynamic allocation.
  • Know how to make a Class.

Code:

The private section of this class with contain a dynamic array and the size of the array.

class myString
{
  private:
          char* str;
          int len;         //length

 public:

    //functions here

};


I'm only gonna make the default constructor for this class because the original string class also has no parameterized constructor. And I'm sure you know how to make a default constructor.

Another important constructor that I did not introduce earlier is the Copy Constructor. 

What is a Copy Constructor?
A copy constructor a very much likely an assignment operator except for the thing that it is called when you initialize the object of that class type e.g.

myString obj("Hello");

Now our copy constructor will initialize our obj to a string that contains "Hello" so basically it is a lot like a parameterized constructor except the thing that we're not sending it all the parameters i.e. size. Just like the constructors, it is called only when the object is created. In its code, it is the same as the assignment operator except for the fact that it doesn't have the check for the length that whether it's already empty array or not. Now let's write the code for it!

//public section
myString(char* obj)
{
     length = strlen(obj);    //using default function to get the size of the inputted data
     str = new char[length+1];

    strcpy( str, obj);    //strcpy is the default function for copying of the character arrays

    //it copies the object on the right into the object on the left

}

You can make another copy constructor whose input is the string and not char*. 

Next on, you can make the assignment operator which does the deep copy and if you don't know how to then please refer to Assignment Operator in C++. Make sure to delete any pre-filled array before you copy. 

Another operator that you can make is the subscript operator [ ]. Here's the code:

char & operator  [] (int i)
{
      return str[i];
}

Try to make the ==, != and + operator too. I'll show you how to make these in the next post. But I'm sure you can make it on your own. :)

Thank you for reading! Best of luck for the assignment! 😝


Share:

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