Pair
Pair is used to combine together two values that may be of different data types.
The pair container is a simple container defined in
Construct a Pair
#include <iostream>
#include <utility>
using namespace std;
int main()
{
// first way
pair<int, char> PAIR1;
PAIR1.first = 100;
PAIR1.second = 'G';
// second way
pair<string, double> PAIR2("GeeksForGeeks", 1.23);
cout << PAIR1.first << " ";
cout << PAIR1.second << endl;
cout << PAIR2.first << " ";
cout << PAIR2.second << endl;
return 0;
}
Member Functions
- make_pair(): This template function allows to create a value pair without writing the types explicitly.
PAIR3 = make_pair("GeeksForGeeks is Best", 4.56);
- swap: This function swaps the contents of one pair object with the contents of another pair object. The pairs must be of the same type.
For two given pairs say pair1 and pair2 of the same type, the swap function will swap the pair1.first with pair2.first and pair1.second with pair2.second.
pair<char, int> pair1 = make_pair('A', 1);
pair<char, int> pair2 = make_pair('B', 2);
pair1.swap(pair2);
- tie(): Unpack the tuple (or pair) values into separate variables.
pair<int, int> pair1 = { 1, 2 };
int a, b;
tie(a, b) = pair1;
Operators(=, ==, !=, >=, <=) in Pair
- using equal(=):
It assigns a new object for a pair object - Comparison (==) operator with pair:
i.e (pari1.first pair2.first) && (pair1.secondpair2.second) - Not equal (!=) operator with pair:
For the given two pairs say pair1 and pair2, the != operator compares the first values of those two pairs i.e. if pair1.first is equal to pair2.first or not, if they are equal then it checks the second values of both. - Logical( >=, <= )operators with pair:
For the given two pairs say pair1 and pair2, the =, >, can be used with pairs as well. It returns 0 or 1 by only comparing the first value of the pair. For pairs like p1=(1,20) and p2=(1,10) p2<p1 should give 0 (as it compares 1st element only & they are equal so it is definitely not less), but that isn’t true. Here the pair compares the second element and if it satisfies then returns 1 (this is only the case when the first element gets equal while using a relational operator > or < only, otherwise these operators work as mentioned above)