Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

make pair
c++
communitycreator

How to use the make_pair() function in C++

Harsh Jain

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;
}
Use make_pair() function in C++

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 pair object is initialized, whose first value is of type int and the second value of type string.
  • In line 7 the make_pair() function is invoked with the required values as its parameters. The function returns the newly created pair object.
  • In lines 10 and 11 the individual pair object values are printed.

RELATED TAGS

make pair
c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring