#include <iostream>
#include <stdexcept>
#include <vector>
template <typename T>
class Queue{
private:
std::vector<T> elements;
public:
Queue(){}//default constructor
T back(){ // return last element
return elements.back();
}
void push(const T& element){//add an element
elements.push_back(element);
}
void pop(){//erase first element
if (elements.empty()) {
throw std::out_of_range("Stack<>::pop(): empty stack");
}
elements.erase( elements.begin() );
}
bool empty(){return elements.empty();}
int size(){return elements.size();
}
T front(){
if (elements.empty()) {
throw std::out_of_range("Stack<>::pop(): empty stack");
}
return elements.front();}
};
template< class T >
//Note that we are passing by reference, so original queue will be erased
void iterate_Queue(Queue<T>& queue){
while(not queue.empty()) {
std::cout << "(" << queue.front()<< ", " << queue.back() << ")";
std::cout << "with size:"<< queue.size() << std::endl;
queue.pop();
}
std::cout << std::endl;
}
typedef Queue<int> intQueue;// It's common to define typedef's in order to simply
//definicions
//typedef Queue< intQueue > queue_intQueue;
typedef Queue< Queue<int> > queue_intQueue;
// ^-- This space isn't opcional, copiler'd think that is a << operador
int main() {
try{
intQueue y;
y.push(1);
y.push(2);
y.push(3);
y.push(4);
iterate_Queue(y);
y.push(15);
iterate_Queue(y);
y.front();//exception, queue is empty
} catch (const std::exception& ex) {
std::cerr << "Exception: " << ex.what() << std::endl;
}
return 0;
}
output:
(1, 4)with size:4
(2, 4)with size:3
(3, 4)with size:2
(4, 4)with size:1
(15, 15)with size:1
Exception: Stack<>::pop(): empty stack
RUN SUCCESSFUL (total time: 244ms)
read more -->
No comments:
Post a Comment