pair & tuple in C++
std::pair bundles exactly two heterogeneous values (.first, .second); std::tuple generalizes to any count, accessed by std::get<N>. Both compare lexicographically out of the box, which makes pairs natural map keys and sort criteria.
make_pair/make_tuple construct with deduction, tie() unpacks (std::tie(a, b) = p;), and structured bindings (auto [x, y] = p;) — C++17's cleanest unpacking — work on both. Returning a pair/tuple beats out-parameters for multi-value results.
pair: two values
std::pair<std::string, int> p{"ada", 36}; — .first and .second name the slots.
tuple: N values
std::tuple<int, std::string, double> t{1, "x", 2.5}; — std::get<0>(t) reads slot zero by index.
Unpack cleanly
auto [name, age] = p; binds both parts at once — structured bindings beat .first/.second soup.
Return multiples
std::pair<bool, int> find(...) returns success plus value — clearer than bool + out-parameter.
#include <iostream>#include <string>#include <utility> int main() { std::pair<std::string, int> p{"ada", 36}; auto [name, age] = p; std::cout << name << " is " << age << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.