C++ Utility::make_pair() Function



The C++ std::utility::make_pair() function is used to create a pair object, which is a simple container for storing two heterogeneous values. It allows you to combine the two values into a single object without explicitly specifying the types.

Syntax

Following is the syntax for std::utility::make_pair() function.

 pair<V1,V2> make_pair (T1&& x, T2&& y); 

Parameters

  • x, y − It indicates the values for the members first and second.

Return Value

It returns a pair object whose elements first and second are set to x and y respectivelly.

Exceptions

If the construction or assignment of type T throws.

Data races

If either (or both) T1 or T2 is an rvalue reference type of a type supporting move semantics, its corresponding argument is modified.

Example 1

In the following example, we are going to consider the basic usage of the make_pair() function.

 #include <iostream> #include <utility> int main() { auto x = std::make_pair(1, "Welcome"); std::cout << "Result : " << x.first << ", " << x.second << std::endl; return 0; } 

Output

Output of the above code is as follows −

 Result : 1, Welcome 

Example 2

Consider the following example, where we are going to use the vector for storing the values.

 #include <iostream> #include <vector> #include <utility> int main() { std::vector < std::pair < int, char >> x; x.push_back(std::make_pair(11, 'A')); x.push_back(std::make_pair(13, 'B')); for (const auto & p: x) { std::cout << "Result : " << p.first << ", " << p.second << std::endl; } return 0; } 

Output

Following is the output of the above code −

 Result : 11, A Result : 13, B 

Example 3

Let's look at the following example, where we are going to use the make_pair() in the map.

 #include <iostream> #include <map> #include <utility> int main() { std::map < int, std::string > x; x.insert(std::make_pair(14, "Hi")); x.insert(std::make_pair(12, "Hello")); for (const auto & p: x) { std::cout << "Result : " << p.first << ", " << p.second << std::endl; } return 0; } 

Output

If we run the above code it will generate the following output −

 Result : 12, Hello Result : 14, Hi 
utility.htm
Advertisements