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!"
#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;
}
Comments
Leave a comment