The queue class is a container that has four member functions with strict behavior as to what those functions perform. A queue can hold zero or more items and
We will describe the various member functions for constructing and querying this container and for inserting, accessing, and removing items from this container.
The the most common constructor simply creates an empty queue:
std::queue<T> identifier{};
As with most containers, you can query if a queue is empty with bool empty() const, and the number of items in the queue std::size_t size() const:
// Prints '0' (false) or '1' (true) std::cout << identifier.empty() << std::endl; // Prints a non-negative integer std::cout << identifier.empty() << std::endl;
The only operation to insert an item into a std::queue<T> is void push( T const &item ) as well as variations on this:
identifier.push( item );
The two operations to access an item in the queue are T front(), which returns a reference to the item in the queue that has been in the queue the longest; and T back(), which returns a reference to the item in the queue that has most recently been inserted into the queue. Because a reference is returned, the items at the front and back can be replaced with a new value:
std::cout << identifier.front() << std::endl; identifier.top() = new_value; // This will now print out the new value... std::cout << identifier.front() << std::endl;
The only operation to remove an item from the queue is void pop() which removes the most item that has been in the queue the longest:
identifier.pop();
The std::queue class does not have member functions that return iterators to items within the queue.
A queue could be implemented as an array as follows:
int queue[128]; std::size_t back_plus_1{ 0 }; std::size_t front{ 0 };
Then,
We can loop through, so as to maximize the usage of the array so if front or back_plus_1 ever reach, in this case, 128, we reset them to zero, while tacking the size, ensuring that there are never more than 128 items placed into the queue.
You can see the use of the std::queue class at replit.com.