user2604504
user2604504

Reputation: 717

What should dequeue return if the queue is empty

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

Answers (3)

Zac Howland
Zac Howland

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

Daniel Frey
Daniel Frey

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

user1804599
user1804599

Reputation:

You have three options:

  • Have a function boost::optional<T> pull() which returns boost::none iff the queue is empty.
  • Throw std::out_of_range or some similar exception.
  • Document pulling from an empty queue as UB (you usually don’t want this).

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

Related Questions