How to use the make_pair() function in C++
The make_pair() function, which comes under the Standard Template Library of C++, is mainly used to construct a pair object with two elements.
In other words, it is a function that creates a value pair without writing the types explicitly.
To use the make_pair() function, you will need to include the <utility> header file in your program, as shown below:
#include <utility>
Syntax
The syntax of the make_pair() function is shown below:
make_pair(value1,value2)
Parameters
The make_pair() function accepts the following two parameters:
value1: The first value to construct the pair from.value2: The second value to construct the pair from.
Return value
The make_pair() function returns a pair object that contains the two elements, value1 and value2.
Code
The code below shows how you can use the make_pair() function in C++:
#include <iostream>#include <utility>using namespace std;int main() {pair<int, string> p;p= make_pair(44, "Edpresso");cout << "Pair created successfully" << endl;cout << "Pair's First Value: " << p.first << endl;cout << "Pair's Second Value: " << p.second;return 0;}
Explanation
The code snippet above performs the following actions:
- Lines 1 to 2 imports the required header files.
- In line 5 the
main()function is initialized. - In line 6 a
pairobject is initialized, whose first value is of typeintand the second value of typestring. - In line 7 the
make_pair()function is invoked with the required values as its parameters. The function returns the newly createdpairobject. - In lines 10 and 11 the individual
pairobject values are printed.