×

Search anything:

Learn to use Pair in C++ STL

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time: 20 minutes

The pair in the C++ STL is a container defined under the <utility> library used to store a pair of two data elements or objects. The two member elements maybe of the same or different types

Definition in <utility>

std::pair is defined as follows under <utility> header file:

template <class T1, class T2> struct pair;

Declaration

Syntax

pair<data_type1, data_type2> Pair_name;

A pair with name a storing two integers and a pair with name b storing one integer and one character are declared as follows:

pair<int, int> a;
pair<int, char> b;    

Properties

Some of the properties of pair include:

  • The first element of the pair is referred to as "first" and the second element of the pair is referred to as "second".
  • Pair can be treated as a valid data type and direct assignment and accession operations can be performed.
  • To access an element of a pair, we use the name of the pair followed by a dot and the position of the element.

Functions

The following functions are applicable for pairs.

  • Operators; (=, ==, !=, >=, <=): These operators can be used as in their normal definition with other pairs.

  • make_pair: It creates a value pair without explicitly specifying the data types.
    Syntax:

Pair_name = make_pair (value1,value2);
  • swap : This function swaps the contents of one pair object with the contents of another pair object. The pairs must be of same type.
    Syntax: pair1.swap(pair2) ;

Illustration of Pair

#include <iostream> 
#include<utility> 
  
using namespace std; 
  
int main() 
{ 
    pair<char, int>a = make_pair('A', 1); 
    pair<char, int>b = make_pair('B', 2); 
  
    cout << "Before swapping: " << endl; 
    cout << "Contents of a = " << a.first << " " << a.second; 
    cout << "Contents of b= " << b.first << " " << b.second; 
    a.swap(b); 
  
    cout << "After swapping: " << endl; 
    cout << "Contents of a = " << a.first << " " << a.second ; 
    cout << "Contents of b = " << b.first << " " << b.second ; 
  
    return 0; 
} 

Output:

Before swapping:
Contents of a = (A, 1)
Contents of b = (B, 2)

After swapping:
Contents of a = (B, 2)
Contents of b = (A, 1)

Question

For swap operation to be performed, what condition must be satisfied?

The pair object must be of same type
The pair object can be of any type
Swapping is between same type objects.
Learn to use Pair in C++ STL
Share this