This post will discuss how to initialize a std::pair in C++.

1. Initialization Constructor

A simple solution to create a std::pair is using its initialization constructor, which takes two arguments corresponding to the first and second member of the pair respectively.

Download  Run Code

Output:

The pair is (John, 25)

2. Using std::make_pair

Another common solution to construct a pair object is using the std::make_pair function, that takes two arguments corresponding to the first and second member of the pair respectively. The advantage of this method is that std::pair template types can be implicitly deduced from its arguments.

Download  Run Code

Output:

The pair is (John, 25)

3. Using Aggregate Initialization

Starting with C++11, you can also initialize a pair from the braced-init-list.

Download  Run Code

Output:

The pair is (John, 25)

 
The following code is the same as above, but uses the direct-list-initialization syntax:

Download  Run Code

Output:

The pair is (John, 25)

4. Copy Constructor

Finally, you can use a copy constructor to initialize a pair object with corresponding members of another pair object.

Download  Run Code

Output:

The pair is (John, 25)

That’s all about initializing a std::pair in C++.