Step 5 of 6
pair and tuple
Sometimes a function needs to return two things, like a minimum and a maximum, or a name and a score. You could make a struct, but for quick jobs the standard library has ready-made ones:
std::pair<A, B>holds two values, called.firstand.second.std::tuple<A, B, C, ...>holds any number of values. You get elementiwithstd::get<i>(t).
Structured bindings unpack either one into named variables in a single line.
#include <iostream>
#include <string>
#include <tuple>
#include <utility>
std::pair<int, int> div_mod(int a, int b) {
return {a / b, a % b}; // braces build the pair
}
std::tuple<std::string, int, double> profile() {
return {"ada", 36, 1.65};
}
int main() {
auto [q, r] = div_mod(17, 5);
std::cout << q << " remainder " << r << "\n";
std::pair<std::string, int> item = {"shield", 1000};
item.second -= 250;
std::cout << item.first << " costs " << item.second << "\n";
auto [name, age, height] = profile();
std::cout << name << " " << age << " " << height << "\n";
std::cout << std::get<1>(profile()) << "\n";
}
3 remainder 2
shield costs 750
ada 36 1.65
36
How it works
return {a / b, a % b};builds the return type from the braces, so you don't have to repeatstd::pair<int, int>.auto [q, r] = ...;declares two new variables. You must useautohere: structured bindings can't name the types one by one.- The number of names must match the number of elements exactly.
When to use a struct instead
.first and .second say nothing about what the values mean. If a pair travels far through your code, a small struct with real field names (name, score) is easier to read. Pairs and tuples are best for short-lived results that get unpacked right away.
Your turn: fill in the blanks.