The Wayback Machine - https://web.archive.org/web/20241010003414/https://www.geeksforgeeks.org/pair-in-cpp-stl/
Open In App

Pair in C++ Standard Template Library (STL)

Last Updated : 12 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 pair container is a simple container defined in <utility> header consisting of two data elements or objects. 

  • The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second).
  • 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.

Syntax: 

pair <data_type1, data_type2> Pair_name

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;
}


Output

100 G

Initializing a Pair: We can also initialize a pair. 

Syntax:

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;
}


Output

GeeksForGeeks 1.23

Note: If not initialized, the first value of the pair gets automatically initialized. 

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. 
Syntax:

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;
}


Output

100 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. 
Syntax:

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;
}


Output

Before 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. 
Syntax: 

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.


Output

1 2
3 2
3 4 a

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;
}


Output

This 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. Syntax:

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)

&list=PLqM7alHXFySGg6GSRmE2INI4k8fPH5qVB

 



Similar Reads

Sort in C++ Standard Template Library (STL)
Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort(). This function internally uses IntroSort. In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By defa
6 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Binary Search in C++ Standard Template Library (STL)
Binary search is a widely used searching algorithm that requires the array to be sorted before search is applied. The main idea behind this algorithm is to keep dividing the array in half (divide and conquer) until the element is found, or all the elements are exhausted.It works by comparing the middle item of the array with our target, if it match
3 min read
Multimap in C++ Standard Template Library (STL)
Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always. These properties of multimap make it very much useful i
6 min read
Queue in C++ Standard Template Library (STL)
Queues are a type of container adaptors that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. Queues use an encapsulated object of deque or list (sequential container class) as its underlying container, providing a specific set of member functions to access its eleme
3 min read
Deque in C++ Standard Template Library (STL)
Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements. Unlike vectors, contiguous storage allocation may not be guaranteed. Double Ended Queues are basically an implementation of the data structure doub
4 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 a singly linked list, we use a forward_list. std::
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 defined inside the <set> header file. Syntax: std:
7 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 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, either directly or through iterators (reference ob
2 min read
Multiset in C++ Standard Template Library (STL)
Multisets are a type of associative containers similar to the set, with the exception that multiple elements can have the same values. Some Basic Functions associated with multiset: begin() - Returns an iterator to the first element in the multiset --> O(1)end() - Returns an iterator to the theoretical element that follows the last element in th
6 min read
Unordered Sets in C++ Standard Template Library
An unordered_set is an unordered associative container implemented using a hash table where keys are hashed into indices of a hash table so that the insertion is always randomized. All operations on the unordered_set take constant time O(1) on an average which can go up to linear time O(n) in the worst case which depends on the internally used hash
6 min read
Difference Between STL and Standard Library in C++
In C++, the term "Standard Library" and "Standard Template Library" are often misinterpreted as the same. Although they sound same with only a single word difference, they refer to the different part of the C++ programming language. In this article, we will learn what's the difference between the C++ Standard Library and Standard Template Library (
3 min read
Algorithm Library Functions in C++ STL
Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Find element in rangestd :: find_if_not : Find elemen
4 min read
<iterator> library in C++ STL
Iterators in C++ STL | Introduction Functions Iterator operations : std :: advance : Advance iteratorstd :: distance : Return distance between iteratorsstd :: begin : Iterator to beginningstd :: end : Iterator to endstd :: prev : Get iterator to previous elementstd :: next : Get iterator to next elementstd :: next vs std :: advanceAll functions in
1 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all < algorithm > library functions : Refer here.Some of the most used algorithms on vectors and most useful one's in Competitive Prog
7 min read
<strings> library in C++ STL
Member functions String.constructor : Construct string object (public member function ).String.destructor : String destructor (public member function )String.operator= : String assignment (public member function ) Iterators Begin : Return iterator to beginning (public member function )End : Return iterator to end (public member function )Advance :
3 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 parameters std::hermite: This function Returns the
2 min read
<regex> library in C++ STL
Main classes These classes encapsulate a regular expression and the results of matching a regular expression within a target sequence of characters. basic_regex: Regular expression object (class template) sub_match: Identifies the sequence of characters matched by a sub-expression (class template) match_results: Identifies one regular expression ma
2 min read
Sorting an array according to another array using pair in STL
We are given two arrays. We need to sort one array according to another. Examples: Input : 2 1 5 4 9 3 6 7 10 8 A B C D E F G H I JOutput : 1 2 3 4 5 6 7 8 9 10 B A F D C G H J E I Here we are sorting second array(a character array) according to the first array (an integer array).We have discussed different ways in below post. Sort an array accordi
6 min read
Queries to check if any pair exists in an array having values at most equal to the given pair
Given a vector of pairs arr[] and Q queries in the form of pairs in an array Queries[], the task for each query is to check if there exists any pair with both the values smaller than those in the pair of the current query. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[][] = {{3, 5}, {2, 7}, {2, 3}, {4, 9}}, Quer
12 min read
std::tuple, std::pair | Returning multiple values from a function using Tuple and Pair in C++
There can be some instances where you need to return multiple values (maybe of different data types ) while solving a problem. One method to do the same is by using pointers, structures or global variables, already discussed here There is another interesting method to do the same without using the above methods,  using tuples (for returning multipl
2 min read
cerr - Standard Error Stream Object in C++
Standard output stream(cout): cout is the instance of the ostream class. cout is used to produce output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream(cout) using the insertion operator(<<). Standard error stream (cerr): cerr is the sta
2 min read
Opening Modes in Standard I/O in C/C++ with Examples
Pre-requisites: File Handling in C++ So far the operations using the C program are done on a prompt/terminal that is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be perfo
13 min read
C++ 03 Standard
The C++ programming language, initially developed by Bjarne Stroustrup in 1983, quickly became one of the most popular programming languages due to its efficiency, flexibility, and support for object-oriented programming. However, as the language evolved, variations and extensions introduced by different compiler vendors led to compatibility issues
4 min read
C++ 23 Standard
C++23, officially known as ISO/IEC 14882:2023, is the latest standardized version of the C++ programming language, published in 2023. As C++ introduces new improvements and features every 3 years in the form of a standard like C++20 introduced powerful features such as concepts, ranges, and coroutines, marking a substantial leap in expressiveness a
6 min read
Why are Standard Iterator Ranges [begin, end) Instead of [begin, end]?
In C++, the Standard Template Library (STL) uses a half-open range convention [begin, end) for iterator ranges. This means the range includes the begin iterator but excludes the end iterator. A common question arises: Why does the STL adopt this convention instead of the fully closed range [begin, end]? In this article, we will learn the advantages
4 min read
What are the Complexity Guarantees of the Standard Containers?
In C++, the Standard Template Library (STL) provides various containers such as std::vector, std::list, std::map, and others, each designed for specific use cases. A very important aspect when we choose the right container for our application is to understand the complexity guarantees they offer for various operations. These guarantees allow us to
3 min read
C++ 11 Standard
C++ 11, officially known as ISO/IEC 14882:2011, is a significant version of the C++ programming language standard, published in 2011. It marked a major fix up of the language, introducing various features and enhancements that improved the usability, performance, and safety of C++ code. Before C++ 11, C++ 03 was the standard, and while it solidifie
5 min read
C++ 98 Standard
C++ 98, officially known as ISO/IEC 14882:1998, was the first international standard for the C++ programming language, published in 1998. This version standardized features that were already widely used in the C++ community and also introduced some new features that laid the foundation for future advancements in the language. Before C++ 98, C++ was
4 min read
Practice Tags :