Pairs and nested pairs in CPP- CPP STL Concept - UCS - Unleash-Coding-Skills

Pairs and nested pairs in CPP- CPP STL Concept - UCS


Pairs are very important to use in CPP because we use pairs concept while solving graphs and trees related problems in competational programming.

Syntax of pair:

The pair is present in header #include <utility> in cpp. you need to include in your program before you use it.

pair<T1,T2> pair1, pair2 ;

Here T1 and T2 can be of any datatype like string ,int etc.

Sample program using pairs concept:

#include <iostream>

using namespace std;    
int main ()
   pair<int,int> pair1, pair3;    //creats pair of integers
   pair<int,string>  pair2;  // creates pair of an integer an a string
   pair1 = make_pair(1, 2);    // insert 1 and 2 to the pair1
   pair2 = make_pair(1, "trial1")  // insert 1 and “Nikhilesh” in pair2
   pair3 = make_pair(2, 4)
   cout<< pair1.first << endl;  // prints 1, 1 being 1st element of pair1
   cout<< pair2.second << endl;  // prints Studytonight 

   if(pair1 == pair3)
     cout<< "Pairs are equal" << endl;
     cout<< "Pairs are not equal" << endl;
   return 0;
In pairs you can perform operations of swap and apply operators like
Operators( == , != , > , < , <= , >= ) : lexicographically compares two pairs.
 First of all to insert into a pair we must use 
The value will be interger or string based on our requirement.

Nested Pairs:


Like this you can have pairs in pair and use them in your program based on your requirement.We will show how to insert in nested pairs by an example.

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;

int main() {
p2=make_pair(2,3); //This is one method to take help 
p1=make_pair(p2,4);//of other pair to make nested pair
p3=make_pair(make_pair(4,5),6);//alternative method to make nested pair
 return 0;


In this way you can insert into pair.
How to print a pair or access a pair.

Generally the terms in pair is accessed as follows
Suppose p2 is our pair to use first element or first parameter in pair we have to access by.
eg: int x= p2.first;


similary for second one we have to use 
 int y = p2.second; 


For accessing the nested pairs as shown above in example problem we have to access just like JSON object or like a structure.

Inside pair we have another pair suppose we have to access it by.Suppose p3 be pair.


It means inside first pair or first paramenter we have again accessing the first parameter in the nested pair.
The storage of pair will be like this.
so to get 5 from the structure we have to use.

By this way we can create nested pairs in CPP which is very important in graphs,trees concept.

Happy Coding..

No comments:

Post a Comment