Pair in STL ( Standard Template Library ) in C++

In this C++ tutorial, we are going to discuss the pairs in C++ STL Standard Template Library, commonly used pair functions, need to use pair template and its use.

What is Pair in STL – C++

Pair is a container which is defined in <utility> header file consists of two data elements.

Syntax:-

    pair < data_type1 , data_type2 > pair_name.

Pair is used to combine two values which may be of the same data type or different data type.

Ex:- We have to put values the enrollment number and name of students in a pair such that after sorting list of students on the basis of roll number their enrollment should remain the same.

    pair < string , int > p;

Here,




string is data_type of the first element which is the name of student.

 int is data_type of second element which is roll number of student.

 p is name of pair.

Some Commonly used functions for pair template

  1.  ” = “ operator assigns value to pair.
  2. make_pair ( value 1 , value 2 ) binds the value 1 and value 2 in pair.
  3. swap swap the contents of pair.

How to use the values in pair?

Suppose we have pair name p, we have to print their values.

To print first value in pair we use pair_name.first

cout<<p.first;                                      // prints the first value in pair p

To print the second value in pair, we use pair_name.second

cout<<p.second;                                   // prints the second value in pair p

We print the first and second value according to our need in program.

C++ Code implementation of Pair template

#include<bits/std++.h>

using namespace std;

   int main()
 {
     int roll;

     string name;
     
     pair<string,int>p[5];
     
      for(int i=0;i<5;i++)
    {
         cin>>name;

         cin>>roll;

        p[i]=make_pair(name, roll);
    }
      
      for(int i=0;i<5;i++)
   {
       cout<<p[i].first<<" "<<p[i].second<<endl;
   }
 }

INPUT

Divyesh 2
Sourabh 6
Rishabh 1
Ravi 4
Kishan 3

OUTPUT

Divyesh 2
Sourabh 6
Rishabh 1
Ravi 4
Kishan 3

Read more tutorials:


Leave a Reply

Your email address will not be published. Required fields are marked *