All about pair STL in c++ for competitive programming( initialization, traversal and methods/functions ) :
pair STL
Important Points:
- It is a simple utility container which consists of a single pair.
- A pair contains values (t1 and t2) which may be of different types.
- It provides a way to store two heterogeneous objects as a single unit.
- Keyword 'first' is used to refer to the first value (t1) and keyword 'second' is used to refer to the second value (t2) .
- A pair can be copied and can be compared with other pairs also.
- Remember to use the header file #include<utility> before using pair STL.
map and pair:
- map STL uses pair only to store (key, value) pairs in it.
- By default, first value (t1) is the key and the second value (t2) is the value associated with the key.
Different ways to initialize a pair STL
1. declaring a pair and using make_pair( ) to make a pair :
pair < int, string > p ;
p = make_pair ( 10, "gamma" ) ;
p = make_pair ( 10, "gamma" ) ;
2. using first and second keyword to make a pair:
pair < int, string > p ;
p.first = 10 ;
p.first = 10 ;
p.second = "gamma" ;
3. initializing during declaration only:
pair < int, string > p ( 10, "gamma" ) ;
4. Initializing from another pair:
pair < int, string > p2 ( 10, "gamma" ) ;
pair < int, string > p ( p2 ) ;
or
p = p2 ;
**don't
worry about the methods / functions used above, i am going to explain
each and every function associated with pair STL below.
All pair STL methods/ functions
pair STL important functions:
1. make_pair( ) : used to make a pair.
2. swap( ) : used to exchange the content of two pairs of same type.
3. operator " = " : used to copy the content of a pair into a new pair.
4. relational operators " = =, ! =, <, >, > =, < = " : used to compare two pairs. (Note: Comparing is done on the basis of key or first value i.e t1)
Other functions:
- tie( )
- get( )
List of all pair STL important functions with example
1. Initializing pairs : pair < int, string > p1, p2 ;
2. Putting elements into them :
p1 = make_pair ( 10, "alpha" ) ; p2 = make_pair ( 90, "beta" ) ;
pair STL traversal method
3. using relational operators to compare them :
if( p1 = = p2 )
cout << "p1 = p2" ;
if( p1 ! = p2 )
cout << "p1 ! = p2" ; //it will be printed if( p1 < p2 )
cout << "p1 < p2" ; //it will be printed if( p1 > p2 )
cout << "p1 > p2" ; if( p1 < = p2 )
cout << "p1 < = p2" ; //it will be printed if( p1 > = p2 )
cout << "p1 > = p2" ; 4. using" = " operator :
//declaring another pair p3
pair < int, string > p3 ;
p3 = p1 ;
Therefore,
p3 = (10, "alpha") 5. swap(p1, p2) // pair p1 and p2 swapped
pair STL traversal method
Let our pair be p :
pair < int, string > p ;
cout << p.first << " " << p.second ;
Comments
Post a Comment