STD :: Pair in C++ STL with Examples

STD :: Pair in C++ STL

1. Pair is a template class in Standard Template Library (STL) in C++.

2. It is not a part of a container.

3. It is defined in <utility> header.

4. It consists of two data elements or objects.

5. The first element is referenced as 'first'.

6. The second element is referenced as 'second'.

7. The order of first and second element is fixed i.e., (firstsecond).

8. Pair is used to combined together two values which may be different in type.

9. Pair provides a way to store two heterogeneous objects as a single unit.

10. Pair can be assignedcopied and compared.

11. We use variable name followed by the dot operator followed by the keyword first or second to access the elements in pair.


Syntax of Pair in C++

pair <T1, T2> P1;

Example:
pair <string, int> pair1;

How to insert value in Pair in C++

Pair1 = make_pair ("Rahul", 16);

How to access Pair Members in C++

pair <string, int> P1;
P1 = make_pair ("Learning Mania", 25);
cout << P1.first << endl;
cout << P1.second << endl;

How to compare two Pairs in C++

You can compare two values of pairs by using the following syntax:

1.       .==      for equals
2.       .>        for greater than
3.       .!=       for not equals to
4.       .<=      for less than or equals to
5.       .<        for less than 
6.       .>=      for greater than or equals to


Example:
#include<iostream>
using namespace std;
class Student{
  string name; int age;
 public:
  void setStudent(string s, int a) {
   name = s;
   age = a;
  }
  void showStudent{
   cout << "\nName: " << name;
   cout << "\nAge: " << age;
  }
 };
 int main(){
  pair <string, int>P1;
  pair <string, string>P2;
  pair <string, float>P3;
  pair <int, Student>P4;
  
  P1 = make_pair("Learning Mania", 25);
  P2 = make_pair("India", "New Delhi");
  P3 = make_pair("Learning C++", 345.5f);
  Student S1;
  S1.setStudent("Aishwarya", 21);
  P4 = make_pair(1, S1);
  
  cout << "/nPair1" << P1.first << "  " << P1.second;
  cout << "/nPair2" << P2.first << "  " << P2.second;
  cout << "/nPair4" << P4.first << "  " ;
  
  Student S2 = P4.second;
  S2.showStudent();
}

<< Previous                                                                                      Next >>
Labels

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.