std::pair and std::tuple

Grouping multiple values

Interview Relevant: Common in solutions

Pair and Tuple

Group multiple values together.

Code Examples

Grouping values with pair and tuple.

cpp
1#include <utility>
2#include <tuple>
3
4// pair - two values
5pair<int, string> p1 = {1, "one"};
6auto p2 = make_pair(2, "two");
7cout << p1.first << " " << p1.second;
8
9// Comparison (lexicographic)
10if (p1 < p2) { }
11
12// Common use: return two values
13pair<int, int> minMax(vector<int>& v) {
14    return {*min_element(v.begin(), v.end()),
15            *max_element(v.begin(), v.end())};
16}
17
18// tuple - any number of values
19tuple<int, double, string> t1 = {1, 3.14, "hello"};
20auto t2 = make_tuple(2, 2.71, "world");
21
22// Access
23int x = get<0>(t1);
24string s = get<2>(t1);
25
26// Structured bindings (C++17)
27auto [a, b, c] = t1;
28
29// tie for assignment
30int i; double d; string str;
31tie(i, d, str) = t1;
32tie(i, ignore, str) = t1;  // Ignore middle value
33
34// Return multiple values
35tuple<int, int, int> getCoords() {
36    return {1, 2, 3};
37}
38auto [x, y, z] = getCoords();

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In