Pair in STL | C++

/Pair in STL | C++

The pair container is a simple container defined in <utility> header consisting of two data elements or objects.

  • The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second).
  • Pair is used to combine together two values which may be different in type. Pair provides a way to store two heterogeneous objects as a single unit.
  • Pair can be assigned, copied and compared. The array of objects allocated in a map or hash_map are of type ‘pair’ by default in which all the ‘first’ elements are unique keys associated with their ‘second’ value objects.
  • To access the elements, we use variable name followed by dot operator followed by the keyword first or second.

 

Commonly used Functions

Here are some function for pair template :

  • Operator = : assign values to a pair.
  • swap : swaps the contents of the pair.
  • make_pair() : create and returns a pair having objects defined by parameter list.
  • Operators( == , != , > , < , <= , >= ) : lexicographically compares two pairs.

 

Example

#include <iostream>
using namespace std;    
    
int main ()
{
  // Value init
  pair <string, double> product2 ("tomatoes",2.30);  

  // Copy constructor  
  pair <string,double> product3 (product2);          
  
  // Creats pair of integers
  pair<int,int> pair1, pair2;

  // Insert 
  pair1 = make_pair(1, 2);     

  pair2.first = 2;
  pair2.second = 4;
  
  // Prints 1, 1 being 1st element of pair1
  cout<< pair1.first << endl;  

  // Comparision
  cout << (pair1 == pair2) << endl; 
  cout << (pair1 != pair2) << endl; 
  cout << (pair1 >= pair2) << endl; 
  cout << (pair1 <= pair2) << endl; 
  cout << (pair1 > pair2) << endl; 
  cout << (pair1 < pair2) << endl; 

  // This function swaps the contents of one pair object with the contents of another pair object. 
  // The pairs must be of same type.
  pair1.swap(pair2); 
  
  return 0;
}

 

 

September 16th, 2019|Categories: Programming|Tags: |
avatar
  Subscribe  
Notify of