Initialize a std::pair in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <utility> int main() { std::pair <std::string, int> p("John", 25); std::cout << "The pair is (" << p.first << ", " << p.second << ")\n"; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <utility> int main() { std::pair <std::string, int> p = std::make_pair("John", 25); std::cout << "The pair is (" << p.first << ", " << p.second << ")\n"; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <utility> int main() { std::pair <std::string, int> p = {"John", 25}; std::cout << "The pair is (" << p.first << ", " << p.second << ")\n"; return 0; } |
Output:
The pair is (John, 25)
The following code is the same as above, but uses the direct-list-initialization syntax:
|
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <utility> int main() { std::pair <std::string, int> p {"John", 25}; std::cout << "The pair is (" << p.first << ", " << p.second << ")\n"; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <utility> int main() { std::pair <std::string, int> p({"John", 25}); std::cout << "The pair is (" << p.first << ", " << p.second << ")\n"; return 0; } |
Output:
The pair is (John, 25)
That’s all about initializing a std::pair in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)