Answer to Question #183706 in C++ for VARUN

Question #183706

Templates and Exception Handling


Implement a Class Template Queue data structure for queue operations such as Full() and Empty() with exception handling. Note: Use templates with exception handling and size of queue is set to 5.

Print: "An queue overflow exception occurred!" or "An queue empty exception occurred!"


1
Expert's answer
2021-04-20T16:19:45-0400
#include <iostream>
#include <queue>
 
using namespace std;
 
template <class T>
class Queue
{
public:
	Queue() {}
	void Add(T item);
	void Pop();
	bool Empty() { return !(data.size()); }
	bool Full() { return data.size() == 5; }
private:
	queue<T> data;
};
 
template <class T>
void Queue<T>::Add(T item)
{
	if (Full()) throw ("An queue overflow exception occurred!");
	else data.push(item);
}
 
template <class T>
void Queue<T>::Pop()
{
	if (Empty()) throw ("An queue empty exception occurred!");
	else data.pop();
}
 
int main()
{
	Queue<int> My;
	cout << "Try to pop from empty Queue." << endl;
	try 
	{
		My.Pop();
	}
	catch (const char* e)
	{
		cout << e << endl;
	}
	try
	{
		for (int i = 0; i < 6; i++)
		{
			cout << "Try to add: " << i+1 << " element." << endl;
			My.Add(i);
		}
	}
	catch (const char* e)
	{
		cout << e << endl;
	}
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS