Reputation: 717
I am writing a queue in C++ (I'm not supposed to use the STL). My dequeue function needs to return the integer it removes from my queue. However, if the queue is empty what should it return? Should I throw an exception and if so which one? Or should I return null (but couldn't that be confusing because that is essentially zero and make it look like I'm returning 0)?
Any help would be greatly appreciated.
Upvotes: 1
Views: 6476
Reputation: 15872
The standard versions of stack
and queue
split the functionality of accessing the next elements and removing them:
stack<int> s;
// put some stuff in s
int i = s.top; // gets the top element
s.pop(); // removes the element you just retrieved in the previous operation
This allows pop()
to be called on a empty container (and do nothing). The top
(or front
and back
function for a queue
) rely on the underlying container (which you can specify) and which typically have undefined behavior if they are called on an empty container.
So, if you want to follow the standard's method for doing it, you can simply say that it is undefined to call it on an empty container. If not, you can do whatever you want (give out your ex-girlfriend's phone number, perhaps?).
Upvotes: 0
Reputation: 56863
Throwing an exception seems most appropriate, since the user should always either know that there is still an element in your queue or check it first by calling .empty()
(assuming you do have such a method).
For the question of what exception you throw: std::logic_error
seems appropriate to me, use a "what"-string to point to your classes' name, the method called and that the queue was empty.
Upvotes: 2
Reputation:
You have three options:
boost::optional<T> pull()
which returns boost::none
iff the queue is empty.std::out_of_range
or some similar exception.I like the first option as it makes it explicit at the type level that a value can be not present, whilst the second and the third options are more at the documentation/contract level, which cannot be easily verified by the compiler.
Upvotes: 1