Core Module
12 min forge
C++ STL Pair
A simple container to store two heterogeneous objects of arbitrary types.
C++ STL Pair
π What is it
std::pair is a structural template that provides a way to store two objects as a single unit. The objects can be of different types.
β‘ When to use
Extremely useful in competitive programming and interview problems for returning multiple values from a function, or storing associated data in maps and sets.
π§ Time complexity
- Access: $O(1)$ (via
firstandsecondmembers). - Comparison: $O(1)$ (lexicographical).
π» Code example
cpp Standard#include <utility> #include <iostream> std::pair<int, string> p = {1, "Forge"}; std::cout << p.first << " " << p.second; // 1 Forge
β Common mistakes
- Confusing
firstandsecond. - Forgetting that pairs are compared lexicographically (first is compared, then second if first is equal).