How to Use pair in C++: Syntax and Examples
In C++,
std::pair is a simple container that holds two values of possibly different types together. You create a pair using std::make_pair or by directly initializing it with two values, then access the elements using first and second members.Syntax
The std::pair template holds two values called first and second. You can create a pair by specifying the types and initializing the values.
std::pair<Type1, Type2> p(value1, value2);creates a pair with two values.auto p = std::make_pair(value1, value2);creates a pair with types deduced automatically.- Access elements with
p.firstandp.second.
cpp
std::pair<Type1, Type2> p(value1, value2);
auto p2 = std::make_pair(value1, value2);
// Access elements
p.first;
p.second;Example
This example shows how to create a pair of a string and an integer, then print both values.
cpp
#include <iostream> #include <utility> // for std::pair and std::make_pair #include <string> int main() { std::pair<std::string, int> person = std::make_pair("Alice", 30); std::cout << "Name: " << person.first << "\n"; std::cout << "Age: " << person.second << "\n"; return 0; }
Output
Name: Alice
Age: 30
Common Pitfalls
Common mistakes when using std::pair include:
- Forgetting to include the
<utility>header. - Mixing up
firstandsecondelements. - Assuming pairs can hold more than two values (use
std::tuplefor that). - Not specifying types explicitly when needed, causing compilation errors.
cpp
#include <iostream> // Missing #include <utility> causes error int main() { // Wrong: no #include <utility> // std::pair<int, int> p(1, 2); // Error: 'pair' not declared // Correct: std::pair<int, int> p(1, 2); std::cout << p.first << ", " << p.second << "\n"; return 0; }
Quick Reference
| Feature | Description |
|---|---|
| std::pair | Template to hold two values of types Type1 and Type2 |
| std::make_pair(value1, value2) | Creates a pair with types deduced from values |
| p.first | Access the first element of the pair |
| p.second | Access the second element of the pair |
| Use | Required to use std::pair and std::make_pair |
Key Takeaways
Use std::pair to store two related values together with different types.
Create pairs with std::make_pair or direct initialization.
Access elements using .first and .second members.
Always include the header to use std::pair.
For more than two values, consider std::tuple instead.