Example of a Deque and Priority Queue as a Template

Example of Deque, regular priority queue, and priority queue as template.

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code is given ‘as is’. I do not take responsibilities of how they are used.

Deque.cc:

#ifndef DEQUE_CC_
#define DEQUE_CC_

#include <iostream>

using namespace std;

template <typename T> class Deque;

template <typename T>
class Node {

	private:

		// Contains the data of the linked Deque node
		T data;	

		// Contains a pointer to the previous item in the linked Deque
		Node<T> *previous;

		// Contains a pointer to the next item in the linked Deque
		Node<T> *next;

	public:

	        friend class Deque<T>;

		//The default constructor doesn't initialize the data members
		Node(void);

		// Create a linked Deque node by setting its data to the input parameter
		// and the next node in the linked Deque to NULL (0)
		Node(const T& new_data);

		Node(const T& new_data,
			 Node<T>* new_previous,
			 Node<T>* new_next);

		T get_data(void);

		Node<T>* get_previous(void);

		Node<T>* get_next(void);

		void set_data(T new_data);	 

		void set_previous(Node<T>* new_previous);

		void set_next(Node<T>* new_next);

		//The default destructor doesn't initialize the data members
		~Node(void);

};

template <typename T>
class Deque {
	private:

		int num_elements;

		// Contains a pointer to the first node in the
		// linked Deque (the head of the Deque)
		Node<T> *head;	

		// Contains a pointer to the last node in the
		// linked Deque (the head of the Deque)
		Node<T> *tail;		

	public:

		// **** Overload Operators ****

		T& operator[] (const int index);

		Deque<T>& operator= (const Deque<T>& new_deque);

		// **** Constructors ****

		// Create a Linked Deque by initializing it's head to NULL (0)
		Deque(void);

		Deque(const Deque<T>& new_deque);

		// Delete all the elements in the linked Deque when the Deque is deleted
		~Deque(void);

		// **** Get Methods ****

		bool is_empty(void) const;

		int size(void) const;

		// **** Set Methods ****

		// **** Print Methods ****

		// **** Methods ****

		void push_front(const T& new_data);

		void push_back(const T& new_data);

		void pop_front(void);

		void pop_back(void);

		T front(void) const;

		T back(void) const;

		void remove_at(int index);

		T& at(const int index);

		//erase

};

/////////////////////////////////////////////////////////
// NODE PUBLIC METHODS
///////////////////////////////////////////////////////////

// **** Constructors ****

template <typename T>
Node<T>::Node(void):
			  previous(NULL),
			  next(NULL){
}

template <typename T>
Node<T>::Node(const T& new_data):
			  data(new_data),
			  previous(NULL),
			  next(NULL){
}

template <typename T>
Node<T>::Node(const T& new_data,
			  Node<T>* new_previous,
			  Node<T>* new_next):
			  data(new_data),
			  previous(new_previous),
			  next(new_next){

}

// **** Get Methods ****
template <typename T>
T Node<T>::get_data(void){
	return data;
}

template <typename T>
Node<T>* Node<T>::get_previous(void){
	return previous;
}

template <typename T>
Node<T>* Node<T>::get_next(void){
	return next;
}

// **** set Methods ****
template <typename T>
void Node<T>::set_data(T new_data){
	data = new_data;
}

template <typename T>
void Node<T>::set_previous(Node<T>* new_previous){
	previous = new_previous;
}

template <typename T>
void Node<T>::set_next(Node<T>* new_next){
	next = new_next;
}

// **** Print Methods ****

// **** Methods ****

// **** Destructor ****

template <typename T>
Node<T>::~Node(void) {
}

/////////////////////////////////////////////////////////
// DEQUE OVERLOAD OPERATORS
///////////////////////////////////////////////////////////
template <typename T>
T& Deque<T>:Shockperator[] (const int index){

	int i  = 0;

	Node<T>* current_node;

	if (index > -1 && index < num_elements && !is_empty()){

		// If index is between the middle and the end of the list, begin  from the end of the list
		// else
		// (index is between the middle and the begin of the list), begin from the beginning of the list
		if (index >= (num_elements / 2) ){

			current_node = tail;

			for (i = num_elements - 1;
				i > index;
				i--, current_node = current_node->previous);

		}else{

			current_node = head;

			for (i = 0;
				i < index;
				i++,current_node = current_node->next);

		}// end if

		return current_node->data;

	}else{

		//cerr << '[X] ERROR: Index out of bounds : ' << index << '/' << (num_elements) << endl;

	}// end if

	return current_node->data;
}

/**
 * operator =
 * @description: deep copy deque
 * @param: new_deque
 * @return: Deque&
 */
template <typename T>
Deque<T>& Deque<T>:Shockperator= (const Deque<T>& new_deque)
{

	num_elements = 0;

    if ( new_deque.head != NULL ){

		Node<T> *current_node = new_deque.head;

		while (current_node != NULL){

			push_back(current_node->data);

			current_node = current_node->next;

			num_elements++;
		}
	}

	// return the existing object
    return *this;
}

/////////////////////////////////////////////////////////
// DEQUE PRIVATE METHODS
///////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////
// DEQUE PUBLIC METHODS
///////////////////////////////////////////////////////////

// **** Constructors ****
template <typename T>
Deque<T>:Grineque(void):
		        num_elements(0),
				head(NULL),
				tail(NULL){
}

template <typename T>
Deque<T>:Grineque(const Deque<T>& new_deque){

	num_elements = 0;

    if ( new_deque.head != NULL ){

		Node<T> *current_node = new_deque.head;

		while (current_node != NULL){

			push_back(current_node->data);

			current_node = current_node->next;

			num_elements++;
		}
	}
}

// **** Get Methods ****

template <typename T>
bool Deque<T>::is_empty() const{
	return((num_elements < 1));
}

template <typename T>
int Deque<T>::size() const{
	return num_elements;
}
// **** set Methods ****

// **** Print Methods ****

// **** Methods ****

template <typename T>
void Deque<T>:Razzush_front(const T& new_data){

    Node<T> *new_node;

    if (head == NULL) {

		 new_node = new Node<T>(new_data, NULL, NULL);

		 head = new_node;

		 tail = new_node;

    } else {

		Node<T> *next_node = head;

		new_node = new Node<T>(new_data, NULL, next_node); 

		head = new_node;

		next_node->set_previous(new_node);

    }

    num_elements++;

}

// Takes an item as a parameter, appends that item to
// the back of the Deque, and returns the Deque
template <typename T>
void Deque<T>:Razzush_back(const T& new_data){

    Node<T> *new_node;

    if (tail == NULL){

		new_node = new Node<T>(new_data, NULL, NULL);

		tail = new_node;

		head = new_node;

    } else {

		Node<T> *previous_node = tail;

		new_node = new Node<T>(new_data, previous_node, NULL);

		tail = new_node;

		previous_node->set_next(new_node);

    }// end if

    num_elements++; 

}

template <typename T>
void Deque<T>:Razzop_front(void){

	if (!is_empty()){

		Node<T> *new_head = head->get_next();

		if (new_head != NULL){

			new_head->set_previous(NULL);

			delete head;

			head = new_head;

			num_elements--;

		}

	}//end if

}

template <typename T>
void Deque<T>:Razzop_back(void){

	if (!is_empty()){

		Node<T> *new_tail = tail->get_previous();

		if (new_tail != NULL){

			new_tail->set_next(NULL);

			delete tail;

			tail = new_tail;

			num_elements--;

		} //end if

	}//end if

}

template <typename T>
T Deque<T>::front() const{
	return (head->data);
}

template <typename T>
T Deque<T>::back() const{
	return (tail->data);
}

template <typename T>
void Deque<T>::remove_at(int index){

	bool is_found = false;

    Node<T> *current_node;

	current_node = head;
	for (int i = 0; current_node != NULL && !is_found; i++){

		if (i == index){

			//Remove from beginning
			if (current_node->previous == NULL){

				head = current_node->next;

				  // Remove from the end
			}else if(current_node->next == NULL){
				current_node->previous->next  = NULL;

			}else{	//Remove from middle

				// Fix previous node's next to skip over the removed node
				current_node->previous->next = current_node->next;

				// Fix next node's previous to skip over the removed node
				current_node->next->previous = current_node->previous;

			}//end if

			delete current_node;

			is_found = true;

		}//end if 

		current_node = current_node->next;

	}//end for	 

/*
	Node<T> *new_node;

    Node<T> *current_node = head;

	bool is_node_found = false;

	for (int i = 0;
		 i < size() &&
		 current_node != NULL
		 && !is_node_found;
		 i++){

		if (i == index){

			is_node_found = true;

			if (current_node == head){

				pop_front();

			}else if (current_node == tail){

				pop_back();

			}else{

				// In order to remove the current node, we have to conect the next node with
				// the node previous to the curent node.
				new_node = current_node->next;

				new_node->set_previous(current_node->get_previous());

				delete(current_node);

				current_node = new_node;

			}//end if

			num_elements--;

		}//end if

		current_node = current_node->next;

	}//end if
*/
}

template <typename T>
T& Deque<T>::at(const int index){

	int i  = 0;

	Node<T>* current_node;

	if (index > -1 && index < num_elements && !is_empty()){

		// If index is between the middle and the end of the list, begin  from the end of the list
		// else
		// (index is between the middle and the begin of the list), begin from the beginning of the list
		if (index >= (num_elements / 2) ){

			current_node = tail;

			for (i = num_elements - 1;
				i > index;
				i--, current_node = current_node->previous);

		}else{

			current_node = head;

			for (i = 0;
				i < index;
				i++,current_node = current_node->next);

		}// end if

		return current_node->data;

	}else{

		//cerr << '[X] ERROR: Index out of bounds : ' << index << '/' << (num_elements) << endl;

	}// end if

	return current_node->data;
}

// **** Destructor ****
template <typename T>
Deque<T>::~Deque(void) {

	Node<T> *next_node;

    Node<T> *current_node = head;

    while (current_node != NULL) {

       	next_node = current_node->next;

        delete(current_node);

        current_node = next_node;

		num_elements--;
    }	

}

#endif

PriorityQueue.cpp:

#include 'PriorityQueue.h'
// First Nodes Created With Constructor

int PriorityQueue::NumOfNodes=1;

// Constructor

PriorityQueue:RazzriorityQueue(void){

    Current.Previous = NULL;

    cout << 'Enter First Element of Queue'
         << endl;

    cin >> Current.Data;

    Current.Next = NULL;

    head = &Current;

    ptr = head;

}

// Function Finding Maximum Priority Element
int PriorityQueue::Maximum(void){

    int Temp;

    ptr = head;

    Temp = ptr->Data;

    while(ptr->Next != NULL){

        if(ptr->Data > Temp){

            Temp = ptr->Data;

		}

        ptr = ptr->Next;
    }

    if(ptr->Next == NULL && ptr->Data > Temp){

		Temp = ptr->Data;

	}

    return(Temp);
}

// Function Finding Minimum Priority Element
int PriorityQueue::Minimum(void){

    int Temp;

    ptr = head;

    Temp = ptr->Data;

    while(ptr->Next != NULL){

        if(ptr->Data < Temp){

            Temp = ptr->Data;

		}

		ptr = ptr->Next;

	}

	if(ptr->Next == NULL && ptr->Data < Temp){

        Temp = ptr->Data;

	}

	return(Temp);
}

// Function inserting element in Priority Queue
void PriorityQueue::Insert(int DT){

    struct Node *newnode;

    newnode = new Node;

    newnode->Data = DT;

    while(ptr->Next != NULL){

		ptr = ptr->Next;

	}

	if(ptr->Next == NULL){

        newnode->Next = ptr->Next;

		ptr->Next = newnode;

	}

	NumOfNodes++;
}

// Function deleting element in Priority Queue
int PriorityQueue:Grinelete(int DataDel){

    struct Node *mynode,*temp;

    ptr = head;

    if(NumOfNodes == 1){

        cout << 'Cannot Delete the only Node'
             << endl;

		return FALSE;
    }

    if(ptr->Data == DataDel){

		/***  Checking condition for deletion of first node  ***/
        temp = ptr;

        ptr = ptr->Next;

        ptr->Previous = NULL;

        //delete temp;

        head = ptr;

        NumOfNodes--;

        return(TRUE);

    }else{

        while(ptr->Next->Next != NULL){

            /***  Checking condition for deletion of   ***/
            /*** all nodes except first and last node  ***/
            if(ptr->Next->Data == DataDel){

                mynode = ptr;

				temp = ptr->Next;

                mynode->Next = mynode->Next->Next;

                mynode->Next->Previous = ptr;

                delete temp;

                NumOfNodes--;

                return(TRUE);

			}

            ptr = ptr->Next;

		}

        if(ptr->Next->Next == NULL && 
           ptr->Next->Data == DataDel){

			/***  Checking condition for deletion of last node  ***/
            temp = ptr->Next;

            delete temp;

            ptr->Next = NULL;

            NumOfNodes--;

            return(TRUE);

		}

	}

    return(FALSE);
}

// Function Searching element in Priority Queue
int PriorityQueue::Search(int DataSearch){

    ptr = head;

    while(ptr->Next != NULL){

        if(ptr->Data == DataSearch){

            return ptr->Data;

		}//end if

		ptr = ptr->Next;
    }

	if(ptr->Next == NULL &&
           ptr->Data == DataSearch){

		return ptr->Data;
	}

    return(FALSE);

}

// Function Displaying elements of Priority Queue
void PriorityQueue:Grinisplay(void){

    ptr = head;

    cout << 'Priority Queue is as Follows:-'
         << endl;

    while(ptr != NULL){

        cout << ptr->Data
             << endl;

        ptr = ptr->Next;

	}

}

// Destructor of Priority Queue
PriorityQueue::~PriorityQueue(void){

	/* Temporary variable */
    struct Node *temp;                      

	while(head->Next != NULL){

        temp = head->Next;

		//    delete head;

        head = temp;
    }

    if(head->Next == NULL){
        delete head;
	}

}

PriorityQueue.h:

#ifndef PRIORITY_QUEUE_H_

#define PRIORITY_QUEUE_H_

#include <iostream>

using namespace std;

#include <iostream>

#include <cstdlib>

enum{

	FALSE = 0,

	TRUE = -1

};

/////////////////////////////////

///// Implements Priority Queue

/////////////////////////////////

// Class Prioriry Queue

class PriorityQueue{

	private:

		// Node of Priority Queue

		struct Node{

        struct Node *Previous;

        int Data;

        struct Node *Next;

		}Current;

		struct Node *head;  // Pointer to Head

		struct Node *ptr;   

        // Pointer for travelling through Queue

		static int NumOfNodes;

        // Keeps track of Number of nodes

	public:

		PriorityQueue(void);

		int Maximum(void);

		int Minimum(void);

		void Insert(int);

		int Delete(int);

		void Display(void);

		int Search (int);

		~PriorityQueue(void);

};

/*

//Main Function

void main()

{

    PriorityQueue PQ;

    int choice;

    int DT;

    while(1)

    {

        cout << 'Enter your choice'
             << endl;

        cout << '1. Insert an element'
             << endl;

        cout << '2. Display a priorty Queue'
             << endl;

        cout << '3. Delete an element'
             << endl;

        cout << '4. Search an element'
             << endl;

        cout << '5. Exit'
             << endl;

        cin >> choice;

        switch(choice)

        {

        case 1:

            cout << 'Enter a Data to enter Queue'
                 << endl;

            cin >> DT;

            PQ.Insert(DT);

            break;

        case 2:

            PQ.Display();

            break;

        case 3:

            {

                int choice;

                cout << 'Enter your choice'
                     << endl;

                cout << '1. Maximum Priority Queue'
                     << endl;

                cout << '2. Minimum Priority Queue'
                     << endl;

                cin >> choice;

                switch(choice)

                {

                case 1:

                    PQ.Delete(PQ.Maximum());

                    break;

                case 2:

                    PQ.Delete(PQ.Minimum());

                    break;

                default:

                    cout << 'Sorry Not a correct choice'
                         << endl;

                }

            }

            break;

        case 4:

            cout << 'Enter a Data to Search in Queue'
                 << endl;

            cin >> DT;

            if(PQ.Search(DT) != FALSE){

                cout << DT
                     << ' Is present in Queue' 
                     << endl;

            }else{

                cout << DT
                     << ' is Not present in Queue'
                     << endl;

            }
            break;

        case 5:

            exit(0);

        default:

            cout << 'Cannot process your choice'
                 << endl;

        }

    }

}

*/
#endif

PriorityQueue.cc:

#ifndef PRIORITY_QUEUE_H_

#define PRIORITY_QUEUE_H_

#include <iostream>

using namespace std;

#include <iostream>

#include <cstdlib>

enum{

	FALSE = 0,

	TRUE = -1

};

/////////////////////////////////

///// Implements Priority Queue

/////////////////////////////////

// Class Prioriry Queue

class PriorityQueue{

	private:

		// Node of Priority Queue

		struct Node{

        struct Node *Previous;

        int Data;

        struct Node *Next;

		}Current;

		struct Node *head;  // Pointer to Head

		struct Node *ptr;   

        // Pointer for travelling through Queue

		static int NumOfNodes;

        // Keeps track of Number of nodes

	public:

		PriorityQueue(void);

		int Maximum(void);

		int Minimum(void);

		void Insert(int);

		int Delete(int);

		void Display(void);

		int Search (int);

		~PriorityQueue(void);

};

/*

//Main Function

void main()

{

    PriorityQueue PQ;

    int choice;

    int DT;

    while(1)

    {

        cout <<'Enter your choice' 
             << endl; 

        cout << '1. Insert an element' 
             << endl; 

        cout << '2. Display a priorty Queue' 
             << endl; 

        cout << '3. Delete an element' 
             << endl; 

        cout << '4. Search an element' 
             << endl; 

        cout << '5. Exit' 
             << endl; 

        cin >> choice;

        switch(choice)

        {

        case 1:

            cout << 'Enter a Data to enter Queue' 
                 << endl; 

            cin >> DT;

            PQ.Insert(DT);

            break;

        case 2:

            PQ.Display();

            break;

        case 3:

            {

                int choice;

                cout << 'Enter your choice' 
                     << endl; 

                cout << '1. Maximum Priority Queue' 
                     << endl; 

                cout << '2. Minimum Priority Queue' 
                     << endl; 

                cin >> choice;

                switch(choice)

                {

                case 1:

                    PQ.Delete(PQ.Maximum());

                    break;

                case 2:

                    PQ.Delete(PQ.Minimum());

                    break;

                default:

                    cout << 'Sorry Not a correct choice' 
                         << endl; 

                }

            }

            break;

        case 4:

            cout << 'Enter a Data to Search in Queue'   
                 << endl; 

            cin >> DT;

            if(PQ.Search(DT) != FALSE){

                cout << DT
                     << ' Is present in Queue' 
                     << endl; 

            }else{

                cout << DT
                     << ' is Not present in Queue' 
                     << endl; 

            break;

        case 5:

            exit(0);

        default:

            cout << 'Cannot process your choice' 
                 << endl; 

        }

    }

}

*/

#endif

If you encounter any problems or errors, please let me know by providing an example of the code, input, output, and an explanation. Thanks.


Share
Leave a comment

Example of Quicksort as a Template by using Overload Operation.

Example of Quicksort as a Template by using Overload Operation.

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code is given ‘as is’. I do not take responsibilities of how they are used.

doublesort.cpp:

/**
  * @Author: Alejandro G. Carlstein
  */
#include <iostream>
#include <fstream>
#include <string>

#include 'Sort.cc'
#include 'Item.h'

using namespace std;

const int MAX_WORDS = 1000;

const string OUTPUT_ALPHA_SORT_FILE = 'short.alpha.txt';
const string OUTPUT_FREQ_SORT_FILE = 'sort.freq.txt';

template <typename T>
T *resize_array(T *array,
				 int &num_elements) { 
	int new_size = num_elements * 2;

    T* new_array = new T[new_size];

    //memcpy( new_array, array, num_elements * sizeof(T) );
	for (int i = 0; i < num_elements; i++){

		//new_array[i].data = array[i].data;
		//new_array[i].frequency = array[i].frequency;
		new_array[i] = array[i];

	}

    num_elements = new_size;

    delete [] array;

    //array = new_array;

	//return new_size;
	return new_array;
}

/**
 * main
 * @description: Lab 10
 * @due: November 24, 2009 1:00PM EST
 */
int main(int argc, char *argv[]){

	int str_len;

	string words[MAX_WORDS];

	Sort<string> str_sort;

	ofstream fout;

	str_len = -1;

	//1. Reads up to 1000 words separated by newline characters   (one at the time)
	for (int i = 0; !cin.fail() && i < MAX_WORDS; i++, str_len++)
		cin >> words[i];

	//2. Print out in alphabetical order to file called short.alpha.txt
	//	2a. one word per line with number of occurences of each word
	//	       listed in parentheses after the word

	fout.open(OUTPUT_ALPHA_SORT_FILE.data());	

	if (fout.is_open()){

		// Bonus A. Use an O(N log N) sorting algorithm, make sure that no
		//                 pre-processing steps exceed O(N log N)
		str_sort.quicksort(words, 0, str_len - 1);			

		for (int i = 0; i < str_len; i++)
			cout << words[i] << endl;

		for (int i = 0; i < str_len; i++)
			fout << words[i] << endl;

	}else{
		cerr << '[X] ERROR: Couldn't open ' << OUTPUT_ALPHA_SORT_FILE << endl;
	}	

	fout.close();

	//3. Print out in frequency order to file caled sort.freq.txt

	fout.open(OUTPUT_FREQ_SORT_FILE.data());	

	if (fout.is_open()){

		int item_size = 2;	

		Item* item = new Item[item_size];

		Sort<Item> item_sort;

		// Record their frequency
		int j = 0;

		item[0].frequency = 1;
		item[0].data = words[0];

		for (int i = 1; i < str_len; i++){

			if (item_size < i){

				// resize array
				item = resize_array(item, item_size);

			}

			if (item[j].data == words[i]){

				//Increase frequency
				item[j].frequency++;

			}else{

				j++;

				item[j].frequency = 1;

				item[j].data = words[i];

			}

		}

		//Order words by frequency
		// Bonus A. Use an O(N log N) sorting algorithm, make sure that no
		//                 pre-processing steps exceed O(N log N)
		item_sort.quicksort(item, 0, str_len);

		for (int i = 0; i < str_len; i++)
			if (item[i].frequency > 0) fout << '(' << item[i].frequency << ') ' << item[i].data << endl;

	}else{
		cerr << '[X] ERROR: Couldn't open ' << OUTPUT_ALPHA_SORT_FILE << endl;
	}	

	fout.close();

	return 0;

}

Item.h:

/**

  * @Author: Alejandro G. Carlstein

  */

#ifndef ITEM_H

#define ITEM_H

#include <string>

using namespace std;

class Item{

	public: 

		int frequency;

		string data;

		//Bonus B. Write a single sort function (but two different comparison

		//		   functions/operators) to produce the two different 

		//		   sorted lists.

		// Compare two Items by their number

		friend bool operator == (const Item& Item1, 

								 const Item& Item2);	

		// Compare two Items by their number

		friend bool operator != (const Item& Item1, 

								 const Item& Item2);	

		// Compare two Items by their number

		friend bool operator <= (const Item& Item1, 

								 const Item& Item2);	

		// Compare two Items by their number

		friend bool operator >= (const Item& Item1, 

								 const Item& Item2);	

		// Compare two Items by their number

		friend bool operator < (const Item& Item1, 

								const Item& Item2);

		// Compare two Items by their number

		friend bool operator > (const Item& Item1, 

								const Item& Item2);	

		Item(void);		 

		Item(const Item& new_item);	

		~Item(void);

};
#endif

Item.cpp:

/**
  * @Author: Alejandro G. Carlstein
  */

#include 'Item.h'

Example of Quicksort as a Template by using Overload Operation.

NOTIFICATION:  These  examples are provided for educational  purposes.   Using this  code is  under your own responsibility and risk. The  code is   given  ‘as is’. I do  not take responsibilities of how they are  used.

doublesort.cpp:
/**
  * @Author: Alejandro G. Carlstein
  */
#include <iostream>
#include <fstream>
#include <string>

#include 'Sort.cc'
#include 'Item.h'

using namespace std;

const int MAX_WORDS = 1000;

const string OUTPUT_ALPHA_SORT_FILE = 'short.alpha.txt';
const string OUTPUT_FREQ_SORT_FILE = 'sort.freq.txt';

template <typename T>
T *resize_array(T *array,
				 int &num_elements) { 
	int new_size = num_elements * 2;

    T* new_array = new T[new_size];

    //memcpy( new_array, array, num_elements * sizeof(T) );
	for (int i = 0; i < num_elements; i++){

		//new_array[i].data = array[i].data;
		//new_array[i].frequency = array[i].frequency;
		new_array[i] = array[i];

	}

    num_elements = new_size;

    delete [] array;

    //array = new_array;

	//return new_size;
	return new_array;
}

/**
 * main
 * @description: Lab 10
 * @due: November 24, 2009 1:00PM EST
 */
int main(int argc, char *argv[]){

	int str_len;

	string words[MAX_WORDS];

	Sort<string> str_sort;

	ofstream fout;

	str_len = -1;

	//1. Reads up to 1000 words separated by newline characters   (one at the time)
	for (int i = 0; !cin.fail() && i < MAX_WORDS; i++, str_len++)
		cin >> words[i];

	//2. Print out in alphabetical order to file called short.alpha.txt
	//	2a. one word per line with number of occurences of each word
	//	       listed in parentheses after the word

	fout.open(OUTPUT_ALPHA_SORT_FILE.data());	

	if (fout.is_open()){

		// Bonus A. Use an O(N log N) sorting algorithm, make sure that no
		//                 pre-processing steps exceed O(N log N)
		str_sort.quicksort(words, 0, str_len - 1);			

		for (int i = 0; i < str_len; i++)
			cout << words[i] << endl;

		for (int i = 0; i < str_len; i++)
			fout << words[i] << endl;

	}else{
		cerr << '[X] ERROR: Couldn't open ' << OUTPUT_ALPHA_SORT_FILE << endl;
	}	

	fout.close();

	//3. Print out in frequency order to file caled sort.freq.txt

	fout.open(OUTPUT_FREQ_SORT_FILE.data());	

	if (fout.is_open()){

		int item_size = 2;	

		Item* item = new Item[item_size];

		Sort<Item> item_sort;

		// Record their frequency
		int j = 0;

		item[0].frequency = 1;
		item[0].data = words[0];

		for (int i = 1; i < str_len; i++){

			if (item_size < i){

				// resize array
				item = resize_array(item, item_size);

			}

			if (item[j].data == words[i]){

				//Increase frequency
				item[j].frequency++;

			}else{

				j++;

				item[j].frequency = 1;

				item[j].data = words[i];

			}

		}

		//Order words by frequency
		// Bonus A. Use an O(N log N) sorting algorithm, make sure that no
		//                 pre-processing steps exceed O(N log N)
		item_sort.quicksort(item, 0, str_len);

		for (int i = 0; i < str_len; i++)
			if (item[i].frequency > 0) fout << '(' << item[i].frequency << ') ' << item[i].data << endl;

	}else{
		cerr << '[X] ERROR: Couldn't open ' << OUTPUT_ALPHA_SORT_FILE << endl;
	}	

	fout.close();

	return 0;

}

Item.h:

/**

  * @Author: Alejandro G. Carlstein

  */

#ifndef ITEM_H

#define ITEM_H

#include <string>

using namespace std;

class Item{

	public: 

		int frequency;

		string data;

		//Bonus B. Write a single sort function (but two different comparison

		//		   functions/operators) to produce the two different 

		//		   sorted lists.

		// Compare two Items by their number

		friend bool operator == (const Item& Item1, 

								 const Item& Item2);	

		// Compare two Items by their number

		friend bool operator != (const Item& Item1, 

								 const Item& Item2);	

		// Compare two Items by their number

		friend bool operator <= (const Item& Item1, 

								 const Item& Item2);	

		// Compare two Items by their number

		friend bool operator >= (const Item& Item1, 

								 const Item& Item2);	

		// Compare two Items by their number

		friend bool operator < (const Item& Item1, 

								const Item& Item2);

		// Compare two Items by their number

		friend bool operator > (const Item& Item1, 

								const Item& Item2);	

		Item(void);		 

		Item(const Item& new_item);	

		~Item(void);

};
#endif

Item.cpp:

/**
  * @Author: Alejandro G. Carlstein
  */

#include 'Item.h'

/**
 * operator ==
 * @description: Compare two Items by their number
 * @param: in, Item1, Item2
 * @return: istream&
 */
bool operator == (const Item& Item1,
				  const Item& Item2){
	 return  (Item1.frequency == Item2.frequency);
}

/**
 * operator !=
 * @description: Compare two Items by their number
 * @param: in, Item1, Item2
 * @return: istream&
 */
bool operator != (const Item& Item1,
				  const Item& Item2){
     return  (Item1.frequency != Item2.frequency);
}

/**
 * operator <=
 * @description: Compare two Items by their number
 * @param: in, Item
 * @return: istream&
 */
bool operator <= (const Item& Item1,
				  const Item& Item2){

    bool b_rtn = false;

	if (Item1.frequency == Item2.frequency){

		b_rtn = (Item1.data > Item2.data);

	}else{
		b_rtn = (Item1.frequency > Item2.frequency);
	}

	return  b_rtn;

}	

/**
 * operator >=
 * @description: Compare two Items by their number
 * @param: in, Item1, Item2
 * @return: istream&
 */
bool operator >= (const Item& Item1,
				  const Item& Item2){

	bool b_rtn = false;

	if (Item1.frequency == Item2.frequency){

		b_rtn = (Item1.data > Item2.data);

	}else{
		b_rtn = (Item1.frequency < Item2.frequency);
	}

	return  b_rtn;
}

/**
 * operator <
 * @description: Compare two Items by their number
 * @param: in, Item1, Item2
 * @return: istream&
 */
bool operator < (const Item& Item1,
				 const Item& Item2){
	return (Item1.frequency > Item2.frequency);
}

/**
 * operator >
 * @description: Compare two Items by their number.
 * @param: in, Item1, Item2
 * @return: istream&
 */
bool operator > (const Item& Item1,
				 const Item& Item2){
	return (Item1.frequency < Item2.frequency);
}

Item::Item(void):
	  frequency(0),
	  data(''){
}

Item::Item(const Item& new_item):
	  frequency(new_item.frequency),
	  data(new_item.data){
}

Item::~Item(void){
}

Sort.cc:

/**
  * @Author: Alejandro G. Carlstein
  * @Course: CS240
  */

#ifndef SORT_CC
#define SORT_CC

#include <iostream>
#include <cstdlib>

//#include 'functions.h'

using namespace std;

//////////////////////////////////////////////////////////////////
// TEMPLATE CLASS SORT   /////////////////////////////////////////
//////////////////////////////////////////////////////////////////

template <typename T>
class Sort{

	private:

		void swap(T* first,
				  T* last);

		void choose_pivot(T array[],
						  int first,
						  int last);

		void partition(T array[],
					   int first,
					   int last,
					   int& pivotIndex,
					   bool order);

	public:

		Sort(void);

		void quicksort(T array[],
					   int first,
					   int last,
					   bool order);

		void selection(T array[],
					   int first,
					   int last,
					   bool order);

	    void insertion(T array[],
					   int first,
					   int last,
					   bool order);

		void bubble(T array[],
					int first,
					int last,
					bool order);

		~Sort(void);
};

///////////////////////////////////////////////////////////////////////////////
//**** OVERLOAD OPERATORS ****
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//**** PRIVATE METHODS ****
///////////////////////////////////////////////////////////////////////////////
template <typename T>
void Sort<T>::swap(T* first,
				   T* last){
	T temp;
	temp = *first;
	*first = *last;
	*last = temp;
}

template <typename T>
void Sort<T>::choose_pivot(T array[],
						  int first,
						  int last){

	int index_pivot = ((first + last) / 2); 

	swap (&array[first], &array[index_pivot]);
}

template <typename T>
void Sort<T>:Razzartition(T array[],
						int first,
						int last,
						int& pivotIndex,
						bool order = false){
	int index_last;
	int index_unknown;

	if (!order){
		// Place pivot in array
		choose_pivot(array, first, last);

		// Copy pivot
		T pivot = array[first];

		// Index of last item
		index_last = first;

		// Index of next item after the first item
		index_unknown = first + 1;

		// Move one item at a time until region is empty
		for (; index_unknown <= last; index_unknown++){					

			// Move item from unknown to proper region
			if (array[index_unknown] < pivot){

				index_last++;

				swap(&array[index_unknown], &array[index_last]);

			}// end if
		}// end for

		// Place pivot into proper position and indicate its location
		swap(&array[first], &array[index_last]);

		pivotIndex = index_last;

	}else{

	}// end if

}

///////////////////////////////////////////////////////////////////////////////
//**** PUBLIC METHODS ****
///////////////////////////////////////////////////////////////////////////////

//**** Constructors ****/

template <typename T>
Sort<T>::Sort(void){
	cout << '[Sort (default)]' << endl;
}

//**** Get Methods ****/

//**** Set Methods ****/

//**** Display Methods ****/

//****  Methods ****/

template <typename T>
void Sort<T>::quicksort(T array[],
					   int first,
					   int last,
					   bool order = false){

	int pivotIndex = 0;

	if (!order){

		if (first < last){

			// Create partition
			partition(array, first, last, pivotIndex, order);

			// Sort regions

			quicksort(array, first, pivotIndex - 1, order);

			quicksort(array, pivotIndex + 1, last, order);
		}

	}else{

	}

}

template <typename T>
void Sort<T>::selection(T array[],
						int first,
						int last,
						bool order){

	int i, j, min;

	i = first;

	for (; i < last; i++){

		min = i;

		for (j = i + 1; j < last; j++){

			if (array[j] < array[min]){

				min = j;

			}// end if

		}//end for

		swap(array[i], array[min]);

	}//end for

}

template <typename T>
void Sort<T>::insertion(T array[],
						int first,
						int last,
						bool order){

	int i, j, min;

	T tmp_to_insert;

	for (i = first + 1; i < last; i++){

		tmp_to_insert = array[i];

		j = i;

		for (; j > first && array[ j - 1] > tmp_to_insert; j--){

			array[j] = array[j - 1];

		}// end for

		array[j] = tmp_to_insert;

	}//end for

}

template <typename T>
void Sort<T>::bubble(T array[],
					 int first,
					 int last,
					 bool order){

	int i,j,min;

	i = last - 1;

	j = first + 1;

	for (; i>= first; i--){

		for (; j <= i; i++){

			if (array[j - 1] > array[j]){

				swap(array[j - 1], array[j]);

			}//end if

		}// end for

	}//end for

}

//**** Destructor ****/

template <typename T>
Sort<T>::~Sort(void){
	cout << '[~Sort(X)]' << endl;
}

#endif

input.txt:

If you encounter any problems or errors, please let me know by providing an example of the code, input, output, and an explanation. Thanks.

/** * operator == * @description: Compare two Items by their number * @param: in, Item1, Item2 * @return: istream& */ bool operator == (const Item& Item1, const Item& Item2){ return (Item1.frequency == Item2.frequency); } /** * operator != * @description: Compare two Items by their number * @param: in, Item1, Item2 * @return: istream& */ bool operator != (const Item& Item1, const Item& Item2){ return (Item1.frequency != Item2.frequency); } /** * operator <= * @description: Compare two Items by their number * @param: in, Item * @return: istream& */ bool operator <= (const Item& Item1, const Item& Item2){ bool b_rtn = false; if (Item1.frequency == Item2.frequency){ b_rtn = (Item1.data > Item2.data); }else{ b_rtn = (Item1.frequency > Item2.frequency); } return b_rtn; } /** * operator >= * @description: Compare two Items by their number * @param: in, Item1, Item2 * @return: istream& */ bool operator >= (const Item& Item1, const Item& Item2){ bool b_rtn = false; if (Item1.frequency == Item2.frequency){ b_rtn = (Item1.data > Item2.data); }else{ b_rtn = (Item1.frequency < Item2.frequency); } return b_rtn; } /** * operator < * @description: Compare two Items by their number * @param: in, Item1, Item2 * @return: istream& */ bool operator < (const Item& Item1, const Item& Item2){ return (Item1.frequency > Item2.frequency); } /** * operator > * @description: Compare two Items by their number. * @param: in, Item1, Item2 * @return: istream& */ bool operator > (const Item& Item1, const Item& Item2){ return (Item1.frequency < Item2.frequency); } Item::Item(void): frequency(0), data(''){ } Item::Item(const Item& new_item): frequency(new_item.frequency), data(new_item.data){ } Item::~Item(void){ }
Sort.cc:

/**
  * @Author: Alejandro G. Carlstein
  * @Course: CS240
  */

#ifndef SORT_CC
#define SORT_CC

#include <iostream>
#include <cstdlib>

//#include 'functions.h'

using namespace std;

//////////////////////////////////////////////////////////////////
// TEMPLATE CLASS SORT   /////////////////////////////////////////
//////////////////////////////////////////////////////////////////

template <typename T>
class Sort{

	private:

		void swap(T* first,
				  T* last);

		void choose_pivot(T array[],
						  int first,
						  int last);

		void partition(T array[],
					   int first,
					   int last,
					   int& pivotIndex,
					   bool order);

	public:

		Sort(void);

		void quicksort(T array[],
					   int first,
					   int last,
					   bool order);

		void selection(T array[],
					   int first,
					   int last,
					   bool order);

	    void insertion(T array[],
					   int first,
					   int last,
					   bool order);

		void bubble(T array[],
					int first,
					int last,
					bool order);

		~Sort(void);
};

///////////////////////////////////////////////////////////////////////////////
//**** OVERLOAD OPERATORS ****
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//**** PRIVATE METHODS ****
///////////////////////////////////////////////////////////////////////////////
template <typename T>
void Sort<T>::swap(T* first,
				   T* last){
	T temp;
	temp = *first;
	*first = *last;
	*last = temp;
}

template <typename T>
void Sort<T>::choose_pivot(T array[],
						  int first,
						  int last){

	int index_pivot = ((first + last) / 2); 

	swap (&array[first], &array[index_pivot]);
}

template <typename T>
void Sort<T>:Razzartition(T array[],
						int first,
						int last,
						int& pivotIndex,
						bool order = false){
	int index_last;
	int index_unknown;

	if (!order){
		// Place pivot in array
		choose_pivot(array, first, last);

		// Copy pivot
		T pivot = array[first];

		// Index of last item
		index_last = first;

		// Index of next item after the first item
		index_unknown = first + 1;

		// Move one item at a time until region is empty
		for (; index_unknown <= last; index_unknown++){					

			// Move item from unknown to proper region
			if (array[index_unknown] < pivot){

				index_last++;

				swap(&array[index_unknown], &array[index_last]);

			}// end if
		}// end for

		// Place pivot into proper position and indicate its location
		swap(&array[first], &array[index_last]);

		pivotIndex = index_last;

	}else{

	}// end if

}

///////////////////////////////////////////////////////////////////////////////
//**** PUBLIC METHODS ****
///////////////////////////////////////////////////////////////////////////////

//**** Constructors ****/

template <typename T>
Sort<T>::Sort(void){
	cout << '[Sort (default)]' << endl;
}

//**** Get Methods ****/

//**** Set Methods ****/

//**** Display Methods ****/

//****  Methods ****/

template <typename T>
void Sort<T>::quicksort(T array[],
					   int first,
					   int last,
					   bool order = false){

	int pivotIndex = 0;

	if (!order){

		if (first < last){

			// Create partition
			partition(array, first, last, pivotIndex, order);

			// Sort regions

			quicksort(array, first, pivotIndex - 1, order);

			quicksort(array, pivotIndex + 1, last, order);
		}

	}else{

	}

}

template <typename T>
void Sort<T>::selection(T array[],
						int first,
						int last,
						bool order){

	int i, j, min;

	i = first;

	for (; i < last; i++){

		min = i;

		for (j = i + 1; j < last; j++){

			if (array[j] < array[min]){

				min = j;

			}// end if

		}//end for

		swap(array[i], array[min]);

	}//end for

}

template <typename T>
void Sort<T>::insertion(T array[],
						int first,
						int last,
						bool order){

	int i, j, min;

	T tmp_to_insert;

	for (i = first + 1; i < last; i++){

		tmp_to_insert = array[i];

		j = i;

		for (; j > first && array[ j - 1] > tmp_to_insert; j--){

			array[j] = array[j - 1];

		}// end for

		array[j] = tmp_to_insert;

	}//end for

}

template <typename T>
void Sort<T>::bubble(T array[],
					 int first,
					 int last,
					 bool order){

	int i,j,min;

	i = last - 1;

	j = first + 1;

	for (; i>= first; i--){

		for (; j <= i; i++){

			if (array[j - 1] > array[j]){

				swap(array[j - 1], array[j]);

			}//end if

		}// end for

	}//end for

}

//**** Destructor ****/

template <typename T>
Sort<T>::~Sort(void){
	cout << '[~Sort(X)]' << endl;
}

#endif

input.txt:

words
The
taxi
took
a
sudden
right
turn
I
heard
gravel
under
the
tires
and
saw
a
brightly
lit
house
silhouetting
dark
trees
and
so
surmised
than
the
driver
had
turned
into
someones
drive
I
knew
that
Derek
had
done
well
for
himself
since
moving
down
south
but
a
tree
lined
drive
was
impressive
It
was
even
more
impressive
that
it
took
nearly
five
minutes
to
actually
wind
our
way
to
the
top
We
pulled
up
in
front
of
a
three
storied
granite
house
It
looked
to
be
several
hundred
years
old
with
pillars
either
side
of
the
tall
hall
door
and
large
Georgian
windows
It
was
probably
built
as
the
country
seat
of
some
lord
or
wealthy
industrialist
I
began
to
think
that
the
driver
had
brought
me
to
the
wrong
place
Are
you
sure
this
is
Morcome
Hall
I
asked
This
is
the
place
guv
came
the
gruff
reply
I
like
to
travel
light
So
all
I
only
had
a
small
hold
all
with
a
couple
of
changes
of
clothes
and
toiletries
in
it
It
seemed
pretty
meagre
compared
to
the
granite
might
of
this
imposing
building
Reaching
to
the
back
seat
behind
me
I
pulled
my
bag
into
the
front
of
the
car
I
looked
out
the
window
again
as
I
slipped
the
strap
over
my
shoulder
This
was
not
what
Id
been
expecting
when
Derek
an
old
school
friend
of
my
big
brothers
had
suggested
Id
come
down
south
and
do
some
work
for
him
At
the
time
the
offer
had
seemed
infinitely
preferable
to
staying
unemployed
at
home
But
now
when
it
came
to
taking
the
last
few
steps
Id
suddenly
gotten
very
cold
feet
Derrick
might
have
done
well
for
himself
recently
But
surely
he
couldnt
have
done
so
well
that
he
could
be
living
in
a
millionaires
mansion
I
asked
the
driver
again
if
this
was
the
correct
address
He
was
a
bit
short
in
his
answer
but
I
had
no
option
except
to
believe
that
he
knew
where
he
was
Id
been
lost
ever
since
wed
left
the
train
station
I
paid
the
fare
got
out
and
looked
around
It
was
a
couple
of
hours
after
sunset
so
I
couldnt
make
out
much
of
the
grounds
But
the
neighbours
either
didnt
have
any
lights
on
or
lived
a
fair
bit
away
I
looked
up
again
at
the
house
as
the
taxi
crunched
gravel
and
pulled
away
The
person
who
lives
here
must
have
a
fortune
So
either
Derrick
had
struck
gold
or
hed
robbed
a
bank
because
there
was
no
way
he
could
have
made
that
much
money
out
of
landscape
gardening
Even
with
the
inflated
prices
they
charge!
Feeling
very
unsure
of
myself
I
climbed
the
steps
to
the
door
There
seemed
to
be
a
party
going
on
as
I
could
hear
loud
music
thumping
away
in
the
depths
of
the
house
Ringing
the
doorbell
seemed
a
waste
of
time
with
all
that
racket
going
on
but
I
did
so
anyway
I
waited
a
couple
of
minutes
There
was
no
answer
I
waited
some
more
Still
nobody
came
So
I
rang
the
bell
again
And
waited
and
thought
that
I
should
go
away
But
I
had
no
place
else
to
go
to
except
back
home
and
I
didnt
want
to
admit
defeat
and
go
running
back
to
my
mother
with
my
tail
between
my
legs
Then
I
noticed
that
the
door
was
slightly
ajar
I
pushed
at
it
gently
and
it
swung
open
a
few
inches
letting
a
wedge
of
yellow
light
spring
out
I
cleared
my
throat
loudly
then
felt
foolish
I
pushed
the
door
again
and
looked
past
it
into
the
hall
All
I
could
see
was
the
black
and
white
tiles
of
the
floor
and
a
small
mahogany
hall
table
against
the
wall
with
a
gold
framed
mirror
hanging
over
it
There
was
nobody
in
sight
Looking
around
one
last
time
to
make
sure
I
was
alone
I
gingerly
put
one
hand
on
to
the
door
and
pushed
again
It
swung
open
fully
and
I
stepped
into
the
large
hall
The
tiles
on
the
floor
were
brightly
polished
reflecting
the
crystal
chandelier
hanging
from
the
high
ceiling
The
hall
was
two
stories
high
and
a
wide
marble
staircase
climbed
up
the
middle
to
a
balcony
that
ran
the
width
of
the
hall
Several
dark
wooden
doors
could
be
seen
on
the
balcony
from
where
I
stood
but
they
were
all
closed
Now
that
Id
entered
I
didnt
know
whether
to
wait
here
to
be
discovered
or
to
do
some
exploring
There
were
two
double
doors
on
either
side
of
the
hall
and
another
smaller
single
door
at
the
back
underneath
the
balcony
All
made
from
the
same
dark
stained
wood
and
all
firmly
closed
It
seemed
especially
empty
with
all
the
party
noises
that
emanated
from
further
back
in
the
house
I
decided
to
play
for
time
by
closing
the
front
door
behind
me
though
I
left
the
lock
on
the
latch
as
Id
found
it
When
I
turned
back
around
again
I
discovered
a
young
lady
dressed
a
long
sleeved
black
dress
over
which
she
wore
a
white
frilly
apron
With
a
frilly
maids
cap
pinned
to
her
black
hair
I
didnt
know
if
she
was
a
real
maid
or
someone
attending
a
fancy
dress
party
dressed
up
as
one
The
skirt
of
her
dress
was
rather
short
and
I
thought
I
could
just
make
out
the
tops
of
her
stockings
peeping
from
under
the
hem
Her
legs
were
long
and
slender
and
her
petite
feet
were
bound
by
thin
leather
straps
and
her
heels
rested
on
four
inch
stilettos
She
was
holding
the
handle
of
the
left
hand
door
which
was
now
half
open
and
looking
directly
at
me
Hhello
I
said
Who
are
you
she
asked
Im
David
I
replied
Im
a
friend
of
Dereks
He
invited
me
to
come
Well
youre
late
the
partys
already
started
she
said
I
was
about
to
explain
that

If you encounter any problems or errors, please let me know by providing an example of the code, input, output, and an explanation. Thanks.

Share
Leave a comment

Example: Binary Search Tree (BST) as Template

Example of Binary Search Tree (BST) as template by using vectors, iterators, and time STL.

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code is given ‘as is’. I do not take responsibilities of how they are used.

Please notice that as an example, the first tree will have all the nodes to the left, the the second tree will have all the nodes to the right, and the third tree will be balance.

Since the second tree have to check first to the left and then to the right it will take more time than the first tree. Also since the third tree is balance it will find faster the values than the second tree

BSTree.cc:

#ifndef BST_CC
#define BST_CC

#include <iostream>

using namespace std;

// Forward declaration of class BST
// By fowarding the declaration, the class BST
// can access to the private data members of BSTNode
// helping to maintain the concept of encapsulation
template <typename T> class BST;

/**
 * BSTNode
 * @description:
 */
template <typename T>
class BSTNode {

	// This is needed to grant class BST access
	// to the private members of BSTNode
	// and help to maintaining the concept of encapsulation
	friend class BST<T>;

	private:
		BSTNode<T>* pLeft;
		T data;
		BSTNode<T>* pRight;

	public:

	//Default Constructor
	BSTNode(void);

	//Constructor
	BSTNode(const T& newData);

	// **** Get Methods ****

	T getData() const;

	// **** Set Methods ****

	void setData(const T& newData);

	//Destructor
	~BSTNode(void);

};

//////////////////////////////////////////////////////////////////

/**
 * BST
 * @description:
 */
template <typename T>
class BST {

	private:	

	int numberOfNodes;

	BSTNode<T> *pRoot;

	T insertNode(BSTNode<T> **pBSTNode,
			     const T& newData);

	T findNode(BSTNode<T> **pBSTNode,
		  	   const T& searchData);

	void displayPreOrderTraversal(BSTNode<T> *pBSTNode) const;

	void displayInOrderTraversal(BSTNode<T> *pBSTNode) const;

	void displayPostOrderTraversal(BSTNode<T> *pBSTNode) const;

	void removeAll(BSTNode<T> *pBSTNode) const;

	public:

	//Default Constructor
	BST(void);

	//Constructor
	BST(const T& newData);

	// **** Get Methods ****

	// **** Set Methods ****

	// **** Methods ****
	T insert(const T& newData);

	T find(const T& searchData);

	int size(void);

	void displayPreOrder(void) const;

	void displayInOrder(void) const;

	void displayPostOrder(void) const;

	//Destructor
	~BST(void);

};

//*****************************************************************************
//**** BSTNODE METHODS ****
//*****************************************************************************

///////////////////////////////////////////////////////////////////////////////
//**** BSTNODE PRIVATE METHODS ****
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//**** BSTNODE PUBLIC METHODS ****
///////////////////////////////////////////////////////////////////////////////

template <typename T>
BSTNode<T>::BSTNode(void){
	//cout << endl << '[Default BSTNode]' << endl;
}

template <typename T>
BSTNode<T>::BSTNode(const T& newData):
					  pLeft(NULL),
					  data(newData),
					  pRight(NULL){
//	cout << endl << '[BSTNode]' << endl;
}

// **** Get Methods ****

/**
 *
 */
template <typename T>
T BSTNode<T>::getData() const{
	return data;
}

// **** Set Methods ****

template <typename T>
void BSTNode<T>::setData(const T& newData){
	data = newData;
}

template <typename T>
BSTNode<T>::~BSTNode(void){
//	cout << endl << '[~BSTNode(X)]' << endl;
}

//*****************************************************************************
//**** BST METHODS ****
//*****************************************************************************

///////////////////////////////////////////////////////////////////////////////
//**** BST PRIVATE METHODS ****
///////////////////////////////////////////////////////////////////////////////

/**
 *
 */
template <typename T>
T BST<T>::insertNode(BSTNode<T> **pBSTNode,
			 		 const T& newData){

	// If subBST is empty then
	// create new BSTNode for the value
	if (*pBSTNode == NULL){

		*pBSTNode = new BSTNode<T>(newData);

		numberOfNodes++;

		return newData;

	}else{

		// If the data is not duplicated
		if (newData != (*pBSTNode)->data){

			// if newData is less than the current node's data
			// then insert a left BSTNode with newData
			// else insert a right BSTNode with newData
			if (newData < (*pBSTNode)->data ){

				insertNode( &( ( *pBSTNode) -> pLeft), newData);		

			}else{

				insertNode( &( ( *pBSTNode) -> pRight), newData);		

			}
		}else{

			T rtnT;

			return rtnT;
		}

	}
}

/**
 *
 */
template <typename T>
T BST<T>::findNode(BSTNode<T> **pBSTNode,
	  	   		   const T& searchData){

	T rtnT;

	// If subBST is empty
	if (*pBSTNode == NULL){

		// Object not found 

		return rtnT;

	}else{

		// If the data is not found
		// Keep searching
		if (searchData != (*pBSTNode)->data){

			// if newData is less than the current node's data
			// then insert a left BSTNode with newData
			// else insert a right BSTNode with newData
			if (searchData < (*pBSTNode)->data ){

				rtnT = findNode( &( ( *pBSTNode) -> pLeft), searchData);		

Just to let you know			}else{

				rtnT = findNode( &( ( *pBSTNode) -> pRight), searchData);		

			}

		}else{

			rtnT = (*pBSTNode)->data;
		}

	}	

	return rtnT;
}

/**
 *
 */
template <typename T>
void BST<T>:GrinisplayPreOrderTraversal(BSTNode<T> *pBSTNode) const{

	if (pBSTNode != NULL){

		// Process Node
		cout << pBSTNode->data << ' ';

		// Traverse left subBST
		displayPreOrderTraversal(pBSTNode->pLeft);

		// Traverse right subBST
		displayPreOrderTraversal(pBSTNode->pRight);

	}
}

/**
 *
 */
template <typename T>
void BST<T>:GrinisplayInOrderTraversal(BSTNode<T> *pBSTNode) const{

	if (pBSTNode != NULL){

		// Traverse left subBST
		displayInOrderTraversal( pBSTNode->pLeft);

		// Process Node
		cout << pBSTNode->data << ' ';

		// Traverse right subBST
		displayInOrderTraversal( pBSTNode->pRight);

	}

}

/**
 *
 */
template <typename T>
void BST<T>:GrinisplayPostOrderTraversal(BSTNode<T> *pBSTNode) const{

	if (pBSTNode != NULL){

		// Traverse left subBST
		displayPostOrderTraversal(pBSTNode->pLeft);

		// Traverse right subBST
		displayPostOrderTraversal(pBSTNode->pRight);

		// Process Node
		cout << pBSTNode->data << ' ';

	}

}

/**
 *
 */
template <typename T>
void BST<T>::removeAll(BSTNode<T> *pBSTNode) const{

	if (pBSTNode != NULL){

		// Traverse left subBST
		removeAll(pBSTNode->pLeft);

		// Traverse right subBST
		removeAll(pBSTNode->pRight);

		delete pBSTNode;

	}

}

///////////////////////////////////////////////////////////////////////////////
//**** BST PUBLIC METHODS ****
///////////////////////////////////////////////////////////////////////////////

/**
 *
 */
template <typename T>
BST<T>::BST(void){
	//cout << endl << '[Default BST]' << endl;
	pRoot = NULL;
	numberOfNodes = 0;
}

/**
 *
 */
template <typename T>
BST<T>::BST(const T& newData){
	//cout << endl << '[BST]' << endl;
	numberOfNodes = 0;
}

// **** Get Methods ****

// **** Set Methods ****

// **** Methods ****

/**
 *
 */
template <typename T>
T BST<T>::insert(const T& newData){
	return insertNode( &pRoot, newData);
}

/**
 *
 */
template <typename T>
T BST<T>::find(const T& searchData){

	//cout << endl << '[find : ' << searchData << ']' << endl;

	return findNode( &pRoot, searchData);
}

/**
 *
 */
template <typename T>
int BST<T>::size(void){
	return numberOfNodes;
}

/**
 *
 */
template <typename T>
void BST<T>:GrinisplayPreOrder(void) const{
	displayPreOrderTraversal( pRoot );
}

/**
 *
 */
template <typename T>
void BST<T>:GrinisplayInOrder(void) const{
	displayInOrderTraversal( pRoot );
}

/**
 *
 */
template <typename T>
void BST<T>:GrinisplayPostOrder(void) const{
	displayPostOrderTraversal( pRoot );
}

/**
 *
 */
template <typename T>
BST<T>::~BST(void){

	cout << endl << '[~BST(X)]' << endl;

//	removeAll(pRoot);

}

#endif

main.cpp:

#include <iostream>
#include <cstdlib>
#include <time.h>
#include <sys/time.h>
#include <vector>
#include <algorithm>
#include 'BSTree.cc'

const int MAX_NUMBERS = 10000;

int main(int argc, char *argv[]){

	cout << endl << '{main}' << endl;

	vector<int> numbers;
	vector<int> reverseNumbers;
	vector<int> randomNumbers;

	BST<int> tree;
	BST<int> reverseTree;
	BST<int> randomTree;

	//Declare at top of main...

	struct timeval initialSimTime, postSimTime;

	double totalSimTime;

	int findMod = 10000;
	int NTimes = 5000;

	cout << 'Create Numbers...' << endl;

	// Insert the first 10,000 odd numbers, in order, into it.
	for (int i = 1; i < MAX_NUMBERS; i += 2)
			reverseNumbers.push_back(i);

	numbers = reverseNumbers;

	reverse(numbers.begin(), numbers.end());

	randomNumbers = numbers;

	random_shuffle(randomNumbers.begin(), randomNumbers.end());

	while(!numbers.empty()){
		tree.insert(numbers.back());
		numbers.pop_back();
	}

	while(!reverseNumbers.empty()){
		reverseTree.insert(reverseNumbers.back());
		reverseNumbers.pop_back();
	}

	while(!randomNumbers.empty()){
		randomTree.insert(randomNumbers.back());
		randomNumbers.pop_back();
	}

	cout << 'Search...' << endl;

///////////////////////////////////////////////////////////////////////

	// Place before the thing you want to time

	gettimeofday(&initialSimTime, NULL);

	cout << endl << 'Values found: ';

	for (int i = 1, j = 0; i < MAX_NUMBERS && j < NTimes; i += 2)
		if (i % findMod)
			if (tree.find(i) == i){
				cout << i << ' ';
				j++;
			}

	cout << endl;

	//Place after the thing you want to time

	gettimeofday(&postSimTime, NULL);

	totalSimTime = (double)(
				   (double)(postSimTime.tv_sec - initialSimTime.tv_sec) * 1000000 +
				   (double)(postSimTime.tv_usec - initialSimTime.tv_usec) ) /
				   (double)1000000;

	//Report how long it takes your program to run each call to that function
	//Output the time it took to do the stuff you wanted to time
	cout << 'Simulation took '<< totalSimTime << ' seconds' << endl << endl;

////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////

	// Place before the thing you want to time

	gettimeofday(&initialSimTime, NULL);

	cout << endl << 'Values found: ';

	for (int i = 1, j = 0; i < MAX_NUMBERS && j < NTimes; i += 2)
		if (i % findMod)
			if (reverseTree.find(i) == i){
				cout << i << ' ';
				j++;
			}

	cout << endl;

	//Place after the thing you want to time

	gettimeofday(&postSimTime, NULL);

	totalSimTime = (double)(
				   (double)(postSimTime.tv_sec - initialSimTime.tv_sec) * 1000000 +
				   (double)(postSimTime.tv_usec - initialSimTime.tv_usec) ) /
				   (double)1000000;

	//Report how long it takes your program to run each call to that function
	//Output the time it took to do the stuff you wanted to time
	cout << '(Reverse) Simulation took '
	     << totalSimTime << ' seconds' << endl << endl;

////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////

	// Place before the thing you want to time

	gettimeofday(&initialSimTime, NULL);

	cout << endl << 'Values found: ';

	for (int i = 1, j = 0; i < MAX_NUMBERS && j < NTimes; i += 2)
		if (i % findMod)
			if (tree.find(i) == i){
				cout << i << ' ';
				j++;
			}

	cout << endl;

	//Place after the thing you want to time

	gettimeofday(&postSimTime, NULL);

	totalSimTime = (double)(
				   (double)(postSimTime.tv_sec - initialSimTime.tv_sec) * 1000000 +
				   (double)(postSimTime.tv_usec - initialSimTime.tv_usec) ) /
				   (double)1000000;

	//Report how long it takes your program to run each call to that function
	//Output the time it took to do the stuff you wanted to time
	cout << '(Random) Simulation took '
	 	 << totalSimTime << ' seconds' << endl << endl;

////////////////////////////////////////////////////////////////////////

/*
	// Search for the first 20 multiples of 1,000
	for (int i = 0; i <= NTimes; i++)
		if (i % findMod == 0)
			if (tree.find(i) == i)
				cout << 'Value ' << i << ' Found!' << endl;

	//Report how long it takes your program to run each call to that function
	//Output the time it took to do the stuff you wanted to time
	cout << 'Simulation took '<< totalSimTime << ' seconds' << endl;

	// Start over with a new BST and insert the same odd numbers,
	// but in reverse order.
	// Again, search for the first 20 multiples of 1,000 and
	// report how long each takes	

	// Insert the first 10,000 odd numbers, in order, into it.
	for (int i = MAX_NUMBERS; i >= 0; i--)
		if (i % 2 != 0)
			reverseTree.insert(i);

	findMod = 1000;
	NTimes = 20;

	// Place before the thing you want to time

	gettimeofday(&initialSimTime, NULL);

	// Search for the first 20 multiples of 1,000
	for (int i = 0; i <= NTimes; i++)
		if (i % findMod)
			if (reverseTree.find(i) == i)
				cout << 'Value ' << i << ' Found!' << endl;

	//Place after the thing you want to time

	gettimeofday(&postSimTime, NULL);

	totalSimTime = (double)(
				   (double)(postSimTime.tv_sec - initialSimTime.tv_sec) * 1000000 +
				   (double)(postSimTime.tv_usec - initialSimTime.tv_usec) ) /
				   (double)1000000;

	//Report how long it takes your program to run each call to that function
	//Output the time it took to do the stuff you wanted to time
	cout << 'Simulation (Reverse) took '<< totalSimTime << ' seconds' << endl;

	// Insert the first 10,000 odd integers in random order into,
	// yet another BST, and run the same test.

	// Insert the first 10,000 odd numbers, in order, into it.

	int i;
	srand(time(NULL));

	bool bMatch[MAX_NUMBERS];

	for (int i = 0; i < MAX_NUMBERS; i++)
		bMatch[i] = false;

	int max = MAX_NUMBERS;
	int min = 0;

	int counter = 0;
	while(randomTree.size() < MAX_NUMBERS){

		i = rand() % (max - 1) + min;

		if ((max - 1) == i)
			max--;

		if ((min + 1) == i)
			min++;

		if (i >= max)
			i -= min;	

		for (int j = 0; j < MAX_NUMBERS; j++)
			cout << ((bMatch[i])? 1: 0);

		if ( i % 2 != 0 && !bMatch[i]){
			bMatch[i] = true;
			cout << ' ' << i;
			randomTree.insert(i);
		}
		cout << endl;

	}

	cout << endl << 'SIZE: ' << randomTree.size() << endl;

	findMod = 1000;
	NTimes = 20;

	// Place before the thing you want to time

	gettimeofday(&initialSimTime, NULL);

	// Search for the first 20 multiples of 1,000
	for (int i = 0; i <= NTimes; i++)
		if (i % findMod)
			if (reverseTree.find(i) == i)
				cout << 'Value ' << i << ' Found!' << endl;

	//Place after the thing you want to time

	gettimeofday(&postSimTime, NULL);

	totalSimTime = (double)(
				   (double)(postSimTime.tv_sec - initialSimTime.tv_sec) * 1000000 +
				   (double)(postSimTime.tv_usec - initialSimTime.tv_usec) ) /
				   (double)1000000;

	//Report how long it takes your program to run each call to that function
	//Output the time it took to do the stuff you wanted to time
	cout << 'Simulation (Random) took '<< totalSimTime << ' seconds' << endl;
*/

	return 0;
}

If you encounter any problems or errors, please let me know by providing an example of the code, input, output, and an explanation. Thanks.

Share
Leave a comment

Example Generating Prime Numbers using Sieve of Eratosthenes Algorithm

Example of how to generate prime numbers using Sieve of Eratosthenes algorithm.

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code is given ‘as is’. I do not take responsibilities of how they are used.

primes.cpp:

#include<iostream>
#include<vector>
#include<stdio.h>
#include<ctime>
#include<math.h>
#include<string.h>
using namespace std;

//
// generatePrimesSlow()
// The array arr store the prime numbers up to and including x
// To test if a number i is prime, see if any prime number
// before i divides i evenly. If no prime number does, i is prime
// and is added to our array of prime numbers.
// Note: We should never see a number less than 2 in our array!
//
void generatePrimesSlow(int x, int * arr, int * amount)
{
   int count = 0; // numbers currently in the array

   for(int i=2; i<=x; i++) {
      bool isPrime = true;
      for (int j=0; j<count; j++) {
         if (i % arr[j] == 0) {
            isPrime = false;
            break;
	 }
      }
      if (isPrime) {
         arr[count] = i;
         count++;
      }
   }
   *amount = count;
}

//
// generatePrimesFast()
// The array arr stores our prime numbers up to and including x
// To generate these numbers, we use the the Sieve of Eratosthenes
// Visit http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
// for the explanation of the algorithm.
//
void generatePrimesFast(int x, int * arr, int * amount)
{
   int num = 2;
   int count = 0;
   bool *boolArr = new bool[x+1];
   //bool boolArr[x];
   memset(boolArr, true, (x+1)*sizeof(bool));
   for(int i=2; i<=x; i++) {
      if (boolArr[i]) {
         arr[count] = i;
         count++;
         int temp = i+i;
         while (temp <= x) {
            boolArr[temp] = false;
            temp += i;
         }
      }
   }
   *amount = count;
}

int main() {
   cout << 'Up to what number would you like to generate primes? ';
   int max;
   cin >> max;
   cout << endl;

   // This will be our array to hold the prime numbers.
   // Notice that this is probably way too much memory, since not every
   // number up to max will be prime
   // In fact, very very few numbers will be, let's try to free up some
   // memory by using some math
   // I think a bound for the number of primes up to N is N/lg(N)
   // Let's try it

   int amount = 0;
   int num_primes;
   if (max > 150) {
      double x = max;
      double actualNumberOfPrimes = x/(log(x)-4);
      //double actualNumberOfPrimes = x/(log(x));
      num_primes = (int) actualNumberOfPrimes;
   }
   else
      num_primes = max;
   int arr[num_primes+1];
   memset(arr,0,sizeof(arr));
   //generatePrimesFast(max, arr, &amount);
   generatePrimesSlow(max, arr, &amount);

   cout << 'Here are the prime numbers from 2 to ' << max << endl;
   for (int i=0; i < amount; i++) {
      cout << arr[i] << endl;
   }
}

If you encounter any problems or errors, please let me know by providing an example of the code, input, output, and an explanation. Thanks.

Share
2 Comments

Example of using Vectors and Iterators STL

Example of using vectors and iterators STL.

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code is given ‘as is’. I do not take responsibilities of how they are used.

CardHolder.cc:

#ifndef CARDSHOLDER_CC
#define CARDSHOLDER_CC

#include <iostream>

using namespace std;

template <typename T, int N> 

class CardsHolder {

	private:

	public:

	insert(N value);

	CardsHolder(void);

	~CardsHolder(void);
};

CardsHolder::CardsHolder(void){
	cout << endl << '[CARDHOLDER]' << endl;
}

CardsHolder::~CardsHolder(void){
	cout << endl << '[~CARDHOLDER]' << endl;
}

#endif

CardHolder.h:

#ifndef CARDSHOLDER
#define CARDSHOLDER

#include <iostream>

using namespace std;

class CardsHolder {

	private:

	public:

	CardsHolder(void);

	insert(int value);

	~CardsHolder(void);
};

CardsHolder::CardsHolder(void){
	cout << endl << '[CARDHOLDER]' << endl;
}

CardsHolder::insert(int value){
}

CardsHolder::~CardsHolder(void){
	cout << endl << '[~CARDHOLDER]' << endl;
}

#endif

mainDriver.cpp:

#include <iostream>
#include <vector>
#include <algorithm>
#include <time.h>

using namespace std;

template <typename T>
void display(const T& c);

template <typename Iterator, typename T>
void display(Iterator first, Iterator last, const T& c); 

/**
 * The purpose of this step is to isolate any problems with 
 * simply including and using the appropriate parts of the STL.
 * Write a program that creates a single instance of 
 * the container you selected, one that holds integers.
 */
int main(int argc, char* argv[]){

	// Your program should contain a single line... 
	// one that instantiates the templated container for integers.
	// ie: vector<int> my_vect
	vector<int> cards_vector;

	// Insert integers 1-52 into your container.
	for (int i = 1; i < 53; i++)
		cards_vector.push_back(i);

	// Print them (using display() - note that this does not use iterators. 
	// Write one using iterators instead if you want to!)
	display(cards_vector);

	cout << endl << '-----------------------------------------------'<< endl;

	// Shuffle the integers (using random_shuffle()).
	srand(time(NULL));
	random_shuffle(cards_vector.begin(), cards_vector.end());	

	// Display them again, confirming that they are shuffled.
	display(cards_vector);

	// In a loop that is terminated by the STL container 
	// becoming empty ( not because you've done it 52 times), 
	// extract the integers from the front of the container, 
	// printing them out one at a time.

	return 0;
}

/**
 * Function template to display elements of any type 
 * (for which the output operator is defined) stored in 
 * a container c (for which [] and size() are defined). 
 *
 * Precondition:  Container is a type parameter. 
 *
 * Postcondition: Values stored in c are output to out.    
 */
template <typename T>
void display(const T& c){

 for (unsigned int i = 0; i < c.size(); i++)    
    cout << c[i] << '  ';   

 cout << endl; 

}

template <typename Iterator, typename T>
void display(Iterator first, Iterator last, const T& c) {
	while (first != last){
    	 cout << c[first] << ' ';
    	 ++first;
    }
}

If you encounter any problems or errors, please let me know by providing an example of the code, input, output, and an explanation. Thanks.

Share
Leave a comment