Learn C++ · lesson 60 of 61 · about 9 minutes
pair, tuple and Structured Bindings
Group a few values together without writing a class, and unpack them in one line.
What you'll learn
- Make and use std::pair and std::tuple
- Return several values from a function
- Unpack values with auto [a, b]
The black knight
On the road home, the black knight blocks the way and challenges the hero to a duel. The player types how many rounds there are, then the hero's score and the knight's in each, like 5 3. The adventure counts the rounds won, lost and drawn, Rounds won 2, lost 1, drawn 1, and says who came out on top: The black knight bows to the hero, The black knight wins the duel or The duel ends in a draw. Each round is two numbers kept together, and the answer is three numbers at once.
Two or three values at once
std::pair<A, B> holds two values, first and second. You've met it already: each item in a std::map is a pair of a key and a value.
std::tuple<A, B, C> holds any number of values. Both are class templates, and std::make_pair or braces build them.
Returning two values
#include <iostream>
#include <utility>
#include <vector>
std::pair<int, int> min_max(const std::vector<int>& v) {
int lo = v[0], hi = v[0];
for (int x : v) {
if (x < lo) lo = x;
if (x > hi) hi = x;
}
return {lo, hi};
}
int main() {
std::pair<int, int> r = min_max({4, 9, 1, 7});
std::cout << r.first << " " << r.second << "\n";
}Output
1 9Structured bindings
auto [lo, hi] = min_max(v); unpacks a pair (or tuple, or struct) into named variables in one line. It's especially neat in loops over a map: for (const auto& [name, score] : scores).
Unpacking
#include <iostream>
#include <map>
#include <string>
#include <tuple>
std::tuple<std::string, int, bool> lookup() {
return {"Ada", 36, true};
}
int main() {
auto [name, age, member] = lookup();
std::cout << name << " " << age << " " << member << "\n";
std::map<std::string, int> scores = {{"Bo", 510}, {"Ada", 340}};
for (const auto& [who, score] : scores) std::cout << who << "=" << score << " ";
std::cout << "\n";
}Output
Ada 36 1
Ada=340 Bo=510Pairs in, a tuple out
Each round goes into a std::vector<std::pair<int, int>> as {heroScore, knightScore}. duel walks the rounds with for (const auto& [heroScore, knightScore] : rounds) and gives back all three counts in one std::tuple<int, int, int>. Then auto [roundsWon, roundsLost, roundsDrawn] = duel(duelRounds); unpacks them into names in main, in the same order as the tuple.
Tip
If the values have real meanings that you use a lot, a small struct with named members is clearer than a tuple. Pairs and tuples are best for quick, short-lived groupings.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.