Container Adapter
Container adapters in the STL are essentially classes that provide a specific interface to an underlying container class, allowing it to be used in a manner different from its original design. These adapters wrap around existing containers and offer a restricted set of operations to achieve specific goals or constraints.
The STL provides three main types of container adapters: stack, queue, and priority_queue.
Anatomy of std::queue
The std::queue container adapter is part of the C++ standard library and is defined in the <queue> header. It is implemented as an adapter over other STL containers, such as std::deque, std::list, or std::vector. The adapter nature means that std::queue provides a higher-level interface built on top of an underlying container, allowing developers to focus on the logical operations of a queue without worrying about the low-level details of memory management.
The primary goal is to simplify the implementation of a queue by offering a high-level interface while abstracting the underlying container.
Characteristics:
- FIFO Behavior: Enforces the first-in, first-out order for elements.
- Adapter Nature: Built on top of an existing container, abstracting implementation details.
Creating a std::queue
To create a std::queue, you declare an instance and optionally specify the underlying container type:
#include <queue>
std::queue<int> myQueue; // Default underlying container is std::deque<int>
std::queue<int, std::vector<int>> myVectorQueue; // Using std::vector<int> as the underlying containerBasic Operations
Enqueueing Elements:
Adding elements to the back of the queue is achieved using the push member function:
myQueue.push(42);Dequeueing Elements:
Removing elements from the front of the queue is done with the pop member function:
myQueue.pop();Functions:
1. Element Access
front():
- Returns a reference to the front element of the queue.
- Access the front element without removing it, you can use the
frontmember function.
Example:
std::queue<int> myQueue:
int frontElement = myqueue.front();2. Capacity
empty():
- Checks if the queue is empty.
Example:
std::queue<int> myQueue;
bool isEmpty = myQueue.empty();size():
- Returns the number of elements in the queue.
Example:
std::queue<int>myQueue;
size_t sizeOfQueue = myQueue.size();3. Modifiers Functions:
push(cont T& value):
- Adds an element to the back of the queue.
Example:
std::queue<int> myQueue;
myQueue.push(42);pop():
- Removes the front element from the queue.
Example:
std::queue<int> myQueue;
myQueue.pop();
Leave a comment
Your email address will not be published. Required fields are marked *


