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.
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.