Learn C++
#include "stlcontainers/pair_tuple.hpp"

pair & tuple in C++

//concept

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.

//how it works
1

pair: two values

std::pair<std::string, int> p{"ada", 36}; — .first and .second name the slots.

2

tuple: N values

std::tuple<int, std::string, double> t{1, "x", 2.5}; — std::get<0>(t) reads slot zero by index.

3

Unpack cleanly

auto [name, age] = p; binds both parts at once — structured bindings beat .first/.second soup.

4

Return multiples

std::pair<bool, int> find(...) returns success plus value — clearer than bool + out-parameter.

//example
#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;
}
Output
ada is 36
1The pair packs a string and an int into one returnable, storable value.
2Structured bindings unpack both slots into named locals in a single declaration.
3The output reads naturally — no .first/.second noise at the use site.
//use cases
Returning success-flag-plus-value from parsers and lookups
Map entries and sorted composite keys via pair ordering
Multi-value returns without defining throwaway structs
tie() comparisons that order several fields with one expression

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.