std::pair in C++: Grouping Two Related Values Together
What is std::pair in C++: Grouping Two Related Values Together? std::pair is a standard utility template defined in `` that binds two heterogeneous values together into a single unit accessed via `.first` and `.second`. In C...
What is std::pair, how is it constructed, and how does structured binding simplify its usage in modern C++?
Explanation & In-Depth Details
```text
┌───────────────────────────────┐
│ std::pair<T1, T2> │
├───────────────┬───────────────┤
│ .first (T1) │ .second (T2) │
└───────────────┴───────────────┘
```
2. Construction Helper:
- `std::make_pair(v1, v2)`: Deduces types automatically.
- Direct initialization: `std::pair<int, std::string>{1, "Admin"}`.
Code Example
#include <iostream>
#include <utility>
#include <string>
std::pair<bool, std::string> authenticateUser(const std::string& user, const std::string& pass) {
if (user == "admin" && pass == "secret123") {
return {true, "Authentication successful (Role: SuperAdmin)"};
}
return {false, "Invalid username or password"};
}
int main() {
// Structured Binding (C++17)
auto [success, message] = authenticateUser("admin", "secret123");
if (success) {
std::cout << "[SUCCESS] " << message << "\n";
} else {
std::cout << "[DENIED] " << message << "\n";
}
std::pair<int, int> coordinates = std::make_pair(1920, 1080);
std::cout << "Resolution: " << coordinates.first << "x" << coordinates.second << "\n";
return 0;
}Interview Question & Tips
A: `std::pair` provides lexicographical comparison operators (`<`, `==`, etc.). It compares `.first` values first; if they are equal, it compares `.second` values.
Q: When should you use `std::tuple` instead of `std::pair`?
A: Use `std::pair` when grouping exactly two values (e.g. key-value pairs). Use `std::tuple` when grouping three or more heterogeneous values together.
Best Practices
• Use `std::pair` when returning multiple outputs (e.g., status and result) from functions.
• Prefer custom named structs over nested pairs (`std::pair<int, std::pair<std::string, double>>`) for maintainability.
This study reference for std::pair in C++: Grouping Two Related Values Together is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: