C++ Program to Implement Pairs in STL


Pair is a simple container which consists of two data object:

‘first’ = The first element is referenced as ‘first’
‘second’ = the second element and the order is fixed (first, second).

Pair can be assigned, compared and copied. It is used to combine together two values which may be different in type.

Syntax is: pair<data type1, data type 2>variable name(datavalue1, datavalue2).

Algorithm

Begin
   Write pair<data type1,data type 2>variable name(datavalue1,datavalue2)
   Print the pairs
End

Example Code

#include<iostream>
using namespace std;
int main() {
   pair <char,int> value('a',7);
   pair <string,double> fruit ("grapes",2.30);
   pair <string,double> food ("pulao",200);
   cout<<"The value of "<<value.first<<" is "<<value.second <<endl;
   cout<<"The price of "<<fruit.first<<" is Rs. "<<fruit.second <<endl;
   cout<<"The price of "<<food.first<<" is Rs. "<<food.second <<endl;
   return 0;
}

Output

The value of a is 7
The price of grapes is Rs. 2.3
The price of pulao is Rs. 200

Updated on: 30-Jul-2019

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements