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 first and second members).
  • 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 first and second.
  • Forgetting that pairs are compared lexicographically (first is compared, then second if first is equal).