Question

The std::queue is implemented with a deque by default. std::deque has the subscript operator, operator[], and is probably implemented with arrays. So why doesn't std::queue have operator[]?

I realize you could have a queue with a list as the underlying container. (std::queue<int, std::list<int>>.) But even if that would make the subscript operator slow, is that really a good reason not to include it? That's the only reason I can think of that it is not included.

Was it helpful?

Solution

Because the definition of queue doesn't support such interface. Queue is a FIFO data structure which means First In First Out. Queue supports enqueue and dequeue operations.

Imagine of queue as pipe : you insert data into one end and from the other end you take it out - one by one. Inserting data is called enqueue and taking them out is called dequeue. The C++ standard library has std::queue which defines both these operations: push() is the name of enqueue operation, and dequeue operation has been splitted into two steps namely front() followed by pop(). The rationale why dequeue has been split into two steps is to give strong exception guarantee1.

Wikipedia explains this briefly,

A queue is a particular kind of collection in which the entities in the collection are kept in order and the principal (or only) operations on the collection are the addition of entities to the rear terminal position and removal of entities from the front terminal position. This makes the queue a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed. This is equivalent to the requirement that once an element is added, all elements that were added before have to be removed before the new element can be invoked. A queue is an example of a linear data structure.

1. If you want to know how exacly it gives strong exception guarantee, then you can start another topic, because it's very long story, and requires lots of patience to understand it properly. I would suggest you to read Exceptional C++ by Herb Sutter for this.

OTHER TIPS

It's a concept issue. In a queue, you add to the back and take from the front, not from the middle

The reason not to include it because a queue is a data structure with enqueue and dequeue operations, not random access. std::queue exists to adapt an existing container into a queue interface, so it only provides the queue interface.

If you want to use [] then use a deque with push_front and back/pop_back not a queue.

Why a double ended queue has it but not a queue doesn't make sense to me either.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top