Deque of Pairs in C++ with Examples
What is a deque?
In C++, the deque is a sequence container and it is also known by the name, double-ended queue. As the name implies, a deque allows insertion and deletion from both ends. Although a deque is similar to a vector, deques are more efficient compared to vectors. In vectors, contiguous storage allocation is guaranteed but this might not be the case with deques. Deque is the special case of a queue as the insertion and deletion operations are allowed at both ends.
Functions associated with a deque:
- push_front(): Used to push elements in the container from the front.
- push_back(): Used to push elements in the container from the back.
- front(): Used to refer to the first element of the container.
- back(): Used to refer to the last element of the container.
What is pair?
- The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second).
- Pair is used to combine together two values that may be different in type. Pair provides a way to store two heterogeneous objects as a single unit.
- Pair can be assigned, copied, and compared. The array of objects allocated in a map or hash_map is of type ‘pair’ by default in which all the ‘first’ elements are unique keys associated with their ‘second’ value objects.
To access the elements, we use variable name followed by dot operator followed by the keyword first or second.
How to access a pair?
The elements of a pair can be accessed by using the dot (.) operator.
auto fistElement = myPair.first;
auto fistElement = myPair.second;
This article focuses upon creating a deque of pairs.
Deque of pairs
Deque of pairs is a deque container in which each element is a pair on its own.
deque<pair<dataType1, dataType2>> myContainer;
dataType1 and dataType2 can be either similar or dissimilar data types
Example 1: Below is the C++ program to implement the deque of pairs.
[ 11 0]
[ 22 0]
[ 33 1]
[ 44 1]
Example 2: Below is the C++ program to implement the deque of pairs.
[ Java 0]
[ GeeksforGeeks 0]
[ GFG 1]
[ Python 1]