Pair in C++ Standard Template Library (STL)
Last Updated :
11 Jan, 2025
Pair is used to combine together two values that may be of different data types. Pair provides a way to store two heterogeneous objects as a single unit. It is basically used if we want to store tuples.
- The first element is referenced as ‘first‘ and the second element as ‘second‘ and the order is fixed (first, second).
- To access them, we use variable name followed by dot operator and finally the keyword ‘first‘ or ‘second‘.
Let’s take a look at an example:
CPP
// CPP program to illustrate Pair in STL
#include <iostream>
#include <utility>
using namespace std;
// Driver Code
int main()
{
// defining a pair
pair<int, char> PAIR1;
// first part of the pair
PAIR1.first = 100;
// second part of the pair
PAIR1.second = 'G';
cout << PAIR1.first << " ";
cout << PAIR1.second << endl;
return 0;
}
Syntax of Pair
The pair container is defined in <utility> header.
pair <data_type1, data_type2> Pair_name
where,
Initializing a Pair
We can also initialize a pair.
pair <data_type1, data_type2> Pair_name (value1, value2) ;
Different ways to initialize pair:
pair g1; //default
pair g2(1, 'a'); //initialized, different data type
pair g3(1, 10); //initialized, same data type
pair g4(g3); //copy of g3
Another way to initialize a pair is by using the make_pair() function.
g2 = make_pair(1, 'a');
Another valid syntax to declare pair is:
g2 = {1, 'a'};
CPP
// CPP program to illustrate
// Initializing of pair STL
#include <iostream>
#include <utility>
using namespace std;
// Driver Code
int main()
{
// defining a pair
pair<string, double> PAIR2("GeeksForGeeks", 1.23);
cout << PAIR2.first << " ";
cout << PAIR2.second << endl;
return 0;
}
Note: If a pair is not initialized, the compiler automatically assigns the first and second members default values according to their types.
C++
// CPP program to illustrate
// auto-initializing of pair STL
#include <iostream>
#include <utility>
using namespace std;
int main()
{
pair<int, double> PAIR1;
pair<string, char> PAIR2;
// it is initialised to 0
cout << PAIR1.first;
// it is initialised to 0
cout << PAIR1.second;
cout << " ";
// // it prints nothing i.e NULL
cout << PAIR2.first;
// it prints nothing i.e NULL
cout << PAIR2.second;
return 0;
}
Output:
00
Member Functions
1) make_pair(): This template function allows to create a value pair without writing the types explicitly.
Pair_name = make_pair (value1,value2);
CPP
// CPP Program to demonstrate make_pair()
// function in pair
#include <iostream>
#include <utility>
using namespace std;
// Driver Code
int main()
{
pair<int, char> PAIR1;
pair<string, double> PAIR2("GeeksForGeeks", 1.23);
pair<string, double> PAIR3;
PAIR1.first = 100;
PAIR1.second = 'G';
PAIR3 = make_pair("GeeksForGeeks is Best", 4.56);
cout << PAIR1.first << " ";
cout << PAIR1.second << endl;
cout << PAIR2.first << " ";
cout << PAIR2.second << endl;
cout << PAIR3.first << " ";
cout << PAIR3.second << endl;
return 0;
}
Output100 G
GeeksForGeeks 1.23
GeeksForGeeks is Best 4.56
2) swap: This function swaps the contents of one pair object with the contents of another pair object. The pairs must be of the same type.
pair1.swap(pair2) ;
For two given pairs say pair1 and pair2 of the same type, the swap function will swap the pair1.first with pair2.first and pair1.second with pair2.second.
CPP
// CPP Program to demonstrate swap()
// function in pair
#include <iostream>
#include <utility>
using namespace std;
// Driver Code
int main()
{
pair<char, int> pair1 = make_pair('A', 1);
pair<char, int> pair2 = make_pair('B', 2);
cout << "Before swapping:\n ";
cout << "Contents of pair1 = " << pair1.first << " "
<< pair1.second;
cout << "Contents of pair2 = " << pair2.first << " "
<< pair2.second;
pair1.swap(pair2);
cout << "\nAfter swapping:\n ";
cout << "Contents of pair1 = " << pair1.first << " "
<< pair1.second;
cout << "Contents of pair2 = " << pair2.first << " "
<< pair2.second;
return 0;
}
OutputBefore swapping:
Contents of pair1 = A 1Contents of pair2 = B 2
After swapping:
Contents of pair1 = B 2Contents of pair2 = A 1
3) tie(): This function works the same as in tuples. It creates a tuple of lvalue references to its arguments i.e., to unpack the tuple (or here pair) values into separate variables. Just like in tuples, here are also two variants of the tie, with and without “ignore”. “ignore” keyword ignores a particular tuple element from getting unpacked.
However, tuples can have multiple arguments but pairs only have two arguments. So, in the case of pair of pairs, unpacking needs to be explicitly handled.
tie(int &, int &) = pair1;
CPP
// CPP code to illustrate tie() in Pair
#include <bits/stdc++.h>
using namespace std;
// Driver Code
int main()
{
pair<int, int> pair1 = { 1, 2 };
int a, b;
tie(a, b) = pair1;
cout << a << " " << b << "\n";
pair<int, int> pair2 = { 3, 4 };
tie(a, ignore) = pair2;
// prints old value of b
cout << a << " " << b << "\n";
// Illustrating pair of pairs
pair<int, pair<int, char> > pair3 = { 3, { 4, 'a' } };
int x, y;
char z;
// tie(x,y,z) = pair3; Gives compilation error
// tie(x, tie(y,z)) = pair3; Gives compilation error
// Each pair needs to be explicitly handled
tie(x,ignore) = pair3;
tie(y, z) = pair3.second;
cout << x << " " << y << " " << z << "\n";
}
// contributed by sarthak_eddy.
Code to illustrate Functions in Pair:
CPP
// CPP program to illustrate pair in STL
#include <iostream>
#include <string>
#include <utility>
using namespace std;
int main()
{
pair<string, int> g1;
pair<string, int> g2("Quiz", 3);
pair<string, int> g3(g2);
pair<int, int> g4(5, 10);
g1 = make_pair(string("Geeks"), 1);
g2.first = ".com";
g2.second = 2;
cout << "This is pair g" << g1.second << " with "
<< "value " << g1.first << "." << endl
<< endl;
cout << "This is pair g" << g3.second << " with value "
<< g3.first
<< "This pair was initialized as a copy of "
<< "pair g2" << endl
<< endl;
cout << "This is pair g" << g2.second << " with value "
<< g2.first << "\nThe values of this pair were"
<< " changed after initialization." << endl
<< endl;
cout << "This is pair g4 with values " << g4.first
<< " and " << g4.second
<< " made for showing addition. \nThe "
<< "sum of the values in this pair is "
<< g4.first + g4.second << "." << endl
<< endl;
cout << "We can concatenate the values of"
<< " the pairs g1, g2 and g3 : "
<< g1.first + g3.first + g2.first << endl
<< endl;
cout << "We can also swap pairs "
<< "(but type of pairs should be same) : " << endl;
cout << "Before swapping, "
<< "g1 has " << g1.first << " and g2 has "
<< g2.first << endl;
swap(g1, g2);
cout << "After swapping, "
<< "g1 has " << g1.first << " and g2 has "
<< g2.first;
return 0;
}
OutputThis is pair g1 with value Geeks.
This is pair g3 with value QuizThis pair was initialized as a copy of pair g2
This is pair g2 with value .com
The values of this pair were changed after initialization.
This is pair g4 with values 5 and 10 made for showing addition.
The sum of the values in this pair is 15.
We can concatenate the values of the pairs g1, g2 and g3 : GeeksQuiz.com
We can also swap pairs (but type of pairs should be same) :
Before swapping, g1 has Geeks and g2 has .com
After swapping, g1 has .com and g2 has Geeks
Time complexity: O(1).
Auxiliary space: O(1).
operators(=, ==, !=, >=, <=) in Pair
We can use operators with pairs as well.
1) using equal(=): It assigns a new object for a pair object.
pair& operator= (const pair& pr);
This Assigns “pr” as the new content for the “pair” object. The first value is assigned the first value of pr and the second value is assigned the second value of pr.
2) Comparison (==) operator with pair: For the two given pairs say pair1 and pair2, the comparison operator compares the “first value and second value of those two pairs i.e. if pair1.first is equal to pair2.first or not” and “if pair1.second is equal to pair2.second or not”.
i.e if ( (pari1.first ==pair2.first) && (pair1.second==pair2.second) )
If any of the two conditions is false then it returns false otherwise true.
3) Not equal (!=) operator with pair: For the given two pairs say pair1 and pair2, the != operator compares the first values of those two pairs i.e. if pair1.first is equal to pair2.first or not, if they are equal then it checks the second values of both.
4) Logical( >=, <= )operators with pair: For the given two pairs say pair1 and pair2, the =, >, can be used with pairs as well. It returns 0 or 1 by only comparing the first value of the pair. For pairs like p1=(1,20) and p2=(1,10) p2<p1 should give 0 (as it compares 1st element only & they are equal so it is definitely not less), but that isn’t true. Here the pair compares the second element and if it satisfies then returns 1 (this is only the case when the first element gets equal while using a relational operator > or < only, otherwise these operators work as mentioned above)
Master C++ with our comprehensive C++ Programming Course Online, perfect for anyone from beginners to advanced learners. Learn everything from the fundamentals to advanced C++ concepts, and apply your knowledge through practical exercises.
Take the Three 90 Challenge! Finish 90% of the course in 90 days, and enjoy a 90% refund. Stay focused, track your progress, and challenge yourself to complete the course! Join today and begin your C++ programming journey!
Similar Reads
Pair in C++ Standard Template Library (STL)
Pair is used to combine together two values that may be of different data types. Pair provides a way to store two heterogeneous objects as a single unit. It is basically used if we want to store tuples. The first element is referenced as 'first' and the second element as 'second' and the order is fi
9 min read
List in C++ Standard Template Library (STL)
Lists are sequence containers that allow non-contiguous memory allocation. As compared to the vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick (constant time). Normally, when we say a List, we talk about a doubly linked list. For implementing
6 min read
Set in C++ Standard Template Library (STL)
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. The std::set class is the part of C++ Standard Template Library (STL) and it is define
7 min read
C++ Standard Template Library (STL)
The C++ Standard Template Library (STL) is a set of template classes and functions that provides the implementation of common data structures and algorithms such as lists, stacks, arrays, sorting, searching, etc. It also provides the iterators and functors which makes it easier to work with algorith
9 min read
Containers in C++ STL (Standard Template Library)
A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them,
2 min read
is_standard_layout template in C++
The std::is_standard_layout template of C++ STL is used to check whether the type is a standard layout or not. It returns a boolean value showing the same. Syntax: template < class T > struct is_standard_layout; Parameters: This template contains single parameter T (Trait class) to check wheth
3 min read
std::is_integral template in C++
The std::is_integral template of C++ STL is used to check whether the given type is integral or not. It returns a boolean value showing the same. Syntax: template <class T> struct is_integral; Template Parameter: This template accepts a single parameter T (Trait class) to check whether T is a
2 min read
is_scalar template in C++
The std::is_scalar template of C++ STL is used to check whether the given type is a scalar type or not. It returns a boolean value showing the same. Syntax: template < class T > struct is_scalar; Parameter: This template accepts a single parameter T (Trait class) to check whether T is a scalar
2 min read
is_pointer Template in C++
The std::is_pointer template of C++ STL is used to check whether the given type is pointer or not. It returns a boolean value showing the same. Syntax: template <class T > struct is_pointer; Parameter: This template accepts a single parameter T (Trait class) to check whether T is a pointer or
2 min read
is_signed template in C++
The std::is_signed template of C++ STL is used to check whether the type is a signed arithmetic type or not. Syntax: template <class T > struct is_signed; Parameters: This template contains single parameter T (Trait class) to check whether T is a signed arithmetic type or not. Return Value: Th
2 min read
std is_object Template in C++
The std::is_object template of C++ STL is used to check whether the given type is object or not. It returns a boolean value showing the same. Syntax: template <class T > struct is_object; Parameter: This template accepts a single parameter T (Trait class) to check whether T is a object type or
2 min read
is_pod template in C++
The std::is_pod template of C++ STL is used to check whether the type is a plain-old data(POD) type or not. It returns a boolean value showing the same. Syntax: template < class T > struct is_pod; Parameter: This template contains single parameter T (Trait class) to check whether T is a pod ty
2 min read
Partial Template Specialization in C++
In C++, template specialization enables us to define specialized versions of templates for some specific argument patterns. It is of two types: Full Template SpecializationPartial Template SpecializationIn this article, we will discuss the partial template specialization in C++ and how it is differe
3 min read
is_class template in C++
The std::is_class template of C++ STL is used to check whether the given type is class or not. It returns a boolean value showing the same. Syntax: template <class T> struct is_class; Parameter: This template accepts single parameter T (Trait class) to check whether T is a class or not. Return
2 min read
std::is_compound Template in C++
The std::is_compound template of C++ STL is used to check the whether the type is a compound type or not. It returns a boolean value showing the same. Syntax: template < class T > struct is_compound; Parameter: This template contains single parameter T (Trait class) to check whether T is a com
2 min read
std is_floating_point Template in C++
The std::is_floating_point template of C++ STL is used to check whether the given type is a floating point value or not. It returns a boolean value showing the same. Syntax: template < class T > struct is_floating_point; Parameter: This template accepts a single parameter T (Trait class) to ch
2 min read
is_final template in C++14
The std::is_final template of C++ STL is used to check whether the type is a final or not. Syntax: template < class T > struct is_final; Parameter: This template contains single parameter T (Trait class) to check whether T is a final type. Return Value: This template returns a boolean value as
2 min read
<numeric> library in C++ STL
Common mathematical functions std::fabs: This function returns the absolute value. std::sqrt: This function returns the square root std::sin: This function returns the sine measured in radians. Special mathematical functions std::beta: This function evaluates the (complete) Beta integral with given
2 min read
std is_union() template in C++
The std::is_union template of C++ STL is used to check whether the given type is union or not. It returns a boolean value showing the same. Syntax: template <class T> struct is_union; Parameter: This template accepts single parameter T (Trait class) to check whether T is a union or not. Return
2 min read