C++20 sections · 1024 units
Open in Course

Creating Pairs

Construction methods

You can create pairs in C++ using two main approaches: make_pair or direct initialization. Using make_pair: pair<int, string> p = make_pair(42, "hello"); The compiler deduces the types from the arguments.

This was important before C++11 when type deduction was limited. Using direct initialization: pair<int, string> p{42, "hello"}; or pair<int, string> p(42, "hello"); With C++11 and later, you can also use auto: auto p = make_pair(42, "hello"); Both methods create identical pairs.

Choose the style that matches your codebase. Modern code often prefers brace initialization for its uniformity across different types.