In: Computer Science
C++ Please write a exmaple of
class template RedBlackTree.h.(It must be template!).
I do not mind about details but please include the basic functions that are necessary for a RedBlackTree.
As per the question we have to write template for RedBlackTree.h file.
As before writing it, let’s understand what is template firstly;
So as per the programming of generic code where we write code which is depend upon some particular type where it can be blue-print of code/program and even formula also.
Let’s see Syntax:
template <class type> return type function-name (parameter list)
{
. .
. .
. .
}
As per this example we have write template for RedBlackTree. As per the question we have freedom to have any class & method to have so for easy understandings let’s take class named
RedBlackTree and another one as RedBlackNode.
Where,
RedBlackTree is going to be container class for this example. And where we can have methods like:-
1. Insert
2. Search
3. Delete
As well as for traversal,
1. First
2. Last
3. Append
And other friend class will be Node of this tree.
For creating tree In this example we have to allocate instance of RedBlackTree().
As this class is defined as temple class it will have method like insert and traversal methods.
Let’s understand template of RedBlackTree class:
template<class key>
Class RedBlackTree {
Public:
RedBlackTree();
// this will help to specify methods like insert and delete
RedBlackTree( int (*(com_val) (key ,key&));
//this will help to specify fuctions like append/delete
RedBlackTree(void (*del_val) (key &val));
//this will help to do both oprations
~ RedBlackTree();
//Destructor
//methods tobe implemented:
void insert (key, &val);
void delete ();
void search ();
.
.
.
//Traversal methods
void first();
void last();
void append();
.
.
.
};
So as we defining template key can be of any type it will work.
As we can also add Marcos for traversal like this:-
#define RedBlackTree_traversal (tree)
{ .
.
. }
#define RedBlackTree_ReverseTravarsal (tree)
{ .
.
. }
As per above we have written a template for RedBlackTree.