In C++, pair is used to combine together two values that may be of different data types or same data types as a single unit. The first element is stored as a data member with name ‘first’ and the second element as ‘second‘.
Example:
CPP
#include <bits/stdc++.h>
using namespace std;
int main() {
// Creating a pair of int and string
pair<int, string> p1 = {1, "Geeks"};
cout << p1.first << ": " << p1.second;
return 0;
}
Explanation: In this program, we created a pair p1 of type int and string with the values {1, “Geeks”}.
Syntax
The pair container is defined in <utility> header file.
pair <T1, T2> p;
where,
- T1: Data type of the first element.
- T2: Data type of the second element.
- p: Name assigned to the pair.
Declaration and Initialization
In C++, pair can be declared and initialized in multiple ways as shown below:
1. Default Initialization
We can declare an empty pair using the below declaration:
pair <T1, T2> p;
2. Declaration and Initialization with Values
We can initialize a pair directly by assigning values to first and second.
pair<T1, T2> p = {v1, v2};
3. Initialization with make_pair()
We can use make_pair() method to initialize pair.
pair<T1, T2> p = make_pair(v1, v2);
Let’s take simple example to demonstrate all ways:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
// Creating an empty pair
pair<int, string> p1;
// Insert values using curly braces {}
pair<int, string> p2 = {1, "Geeks"};
// Insert values using make_pair method
pair<int, string> p3 = make_pair(2, "ForGeeks");
cout << p2.first << " " << p2.second << endl;
cout << p3.first << " " << p3.second;
return 0;
}
Explanation: In the above program, we created three pairs:
- pair<int, string> p1 creates an empty pair of type int and string.
- pair<int, string> p2 = {1, “Geeks”} creates a pair and initializes it with the values {1, “Geeks”} using curly braces.
- pair<int, string> p3 = make_pair(2, “ForGeeks”) creates a pair and initializes it with the values {2, “ForGeeks”} using the make_pair method.
All the values should match the type of the pair, otherwise, a compiler error will be displayed.
Note: If a pair is not initialized, the compiler automatically assigns the first and second members default values according to their types.
Basic Operations
The basic operations on pairs are show below:
1. Accessing Values
In pair, first and second values are stored as data members. So, we can access them by using their name with (.) operator.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
pair<int, string> p = {1, "Geeks"};
// Accessing the elements of the pair
cout << p.first << " " << p.second;
return 0;
}
Explanation: In the above program, p.first accesses the first values of the pair, which is 1. p.second accesses the second element of the pair, which is “Geeks“.
2. Update Values
We update the elements of pair like accessing elements from pair but in place of access, we just assign new value using assignment operator.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
pair<int, string> p = {1, "Geeks"};
// Update first and second value of pair
p.first = 2;
p.second = "ForGeeks";
cout << p.first << " " << p.second;
return 0;
}
Explanation: In the above code, p.first = 2 directly changes the first value of the pair to 2, and p.second = “ForGeeks”; directly changes the second value of the pair to “ForGeeks”.
3. Compare Pairs
Just like other data types, we can use relational operators with pairs. They initially compare the first value. If it does not give result, then second value is compared. The following table describes the behaviour of these operators for pairs:
Operator | Description |
---|
== | Returns true if both pairs are equal, otherwise false. |
---|
!= | Returns true if pairs are not equal, otherwise false. |
---|
> | Returns true if the LHS pair is greater than the RHS pair, otherwise false. |
---|
< | Returns true if the left operand is less than the right operand, otherwise false. |
---|
>= | Returns true if the left operand is greater than or equal to the right operand, otherwise false. |
---|
<= | Returns true if the left operand is less than or equal to the right operand, otherwise false. |
---|
Example:
C++
#include <iostream>
using namespace std;
int main() {
pair<int, int> p1 = {3, 5};
pair<int, int> p2 = {3, 7};
pair<int, int> p3 = {2, 5};
// printing result of comparision
cout << boolalpha;
cout << "p1 == p2: " << (p1 == p2) << endl;
cout << "p1 != p3: " << (p1 != p3) << endl;
cout << "p1 > p3: " << (p1 > p3) << endl;
cout << "p1 < p2: " << (p1 < p2) << endl;
cout << "p1 >= p3: " << (p1 >= p3) << endl;
cout << "p3 <= p1: " << (p3 <= p1);
return 0;
}
Outputp1 == p2: false
p1 != p3: true
p1 > p3: true
p1 < p2: true
p1 >= p3: true
p3 <= p1: true
Unpacking a Pair
We can store extract and store the two values of the pair in two different variables of same type using tie() function.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
pair<int, string> p = {1, "Geeks"};
// Variables to store extracted values
int a;
string s;
// Extracting values using tie()
tie(a, s) = p;
cout << "First value: " << a << endl;
cout << "Second value: " << s;
return 0;
}
OutputFirst value: 1
Second value: Geeks
Explanation: In this program, the first and second value of the pair p is extracted into the variable a and s using the function tie().
Common Applications of pairs
A pair is commonly used for the following purposes:
- Returning multiple values from functions.
- Storing key-value pairs in other containers, especially maps.
- Sorting containers on the basis of multiple criteria.
Similar Reads
Map in C++ STL
In C++, maps are associative containers that store data in the form of key value pairs sorted on the basis of keys. No two mapped values can have the same keys. By default, it stores data in ascending order of the keys, but this can be changes as per requirement. Example: [GFGTABS] C++ #include <
8 min read
std::make_pair() in C++
In C++, make_pair() is a standard library function used to construct a key-value pair from the given arguments. The type of the pair constructed is deduced automatically from the type of arguments. In this article, we will learn about make_pair() function in C++. Letâs take a quick look at a simple
3 min read
merge() in C++ STL
C++ offers in its STL library a merge() which is quite useful to merge sort two containers into a single container. It is defined in header "algorithm". It is implemented in two ways. Syntax 1 : Using operator "<" Template : template outiter merge (initer1 beg1, initer1 end1, initer2 beg2, initer
5 min read
Stack in C++ STL
In C++, stack container follows LIFO (Last In First Out) order of insertion and deletion. It means that most recently inserted element is removed first and the first inserted element will be removed last. This is done by inserting and deleting elements at only one end of the stack which is generally
5 min read
Set in C++ STL
In C++, sets are associative container which stores unique elements in some sorted order. By default, it is sorted ascending order of the keys, but this can be changed as per requirement. It provides fast insertion, deletion and search operations. Example: [GFGTABS] C++ #include <iostream> #in
7 min read
std::min in C++
The std::min() is used to find the minimum element among the given elements. It is the built-in function of C++ STL defined inside <algorithm> header file. In this article, we will learn how to use std::min() function in C++. std::min() Function Signaturetemplate< class T, class Compare
3 min read
std::search in C++
std::search is defined in the header file <algorithm> and used to find out the presence of a subsequence satisfying a condition (equality if no such predicate is defined) with respect to another sequence. It searches the sequence [first1, last1) for the first occurrence of the subsequence defi
4 min read
set operator= in C++ STL
The â=â is an operator in C++ STL which copies (or moves) a set to another set and set::operator= is the corresponding operator function. There are three versions of this function: The first version takes reference of an set as an argument and copies it to an set. Syntax: ums1.operator=(set &set
2 min read
map operator= in C++ STL
The map::operator= is a built function in C++ STL which assigns contents of a container to a different container, replacing its current content. Syntax: map1_name = map2_name Parameters: The map on the left is the container in which the map on the right is to be assigned by destroying the elements o
2 min read
Map of pairs in STL
Map in STL is used to hash key and value. We generally see map being used for standard data types. We can also use map for pairs. For example consider a simple problem, given a matrix and positions visited, print which positions are not visited. // C++ program to demonstrate use of map // for pairs
2 min read