Lesson 16 · 16 of 20
Pairs and structured bindings · C++
Group two values with std::pair in C++, return them together from a function and unpack them with C++17 structured bindings.

`std::pair` keeps two values together, which can be of different types: a product and its price. You reach them with `first` and `second`. It lives in <utility>.
`std::make_pair` builds a pair and works out the types from the values, so you do not have to write them.
A function returns a single value, but that value can be a pair: minMax hands back both the lowest and the highest temperature with return {lo, hi};.
C++17 structured bindings, auto [coldest, hottest] = minMax(week);, give a name to each part of the pair. It reads much better than result.first and result.second.
They really shine when walking through a map, whose elements are pairs: for (const auto& [player, count] : goals) pulls out each player's name and goals, in alphabetical order.
Code · main.cpp
#include <iostream>#include <map>#include <string>#include <utility>#include <vector>// A function can return two results inside a pair.std::pair<int, int> minMax(const std::vector<int>& values) { int lo = values[0], hi = values[0]; for (int v : values) { if (v < lo) lo = v; if (v > hi) hi = v; } return {lo, hi};}int main() { // A pair holds two values, which may have different types. std::pair<std::string, double> product = {"Headphones", 59.99}; std::cout << product.first << " cost " << product.second << " euros\n"; auto city = std::make_pair("Valencia", 26); // make_pair deduces the types std::cout << city.first << ": " << city.second << " C\n"; // Structured bindings give a name to each part. std::vector<int> week = {19, 24, 17, 28, 22}; auto [coldest, hottest] = minMax(week); std::cout << "This week: from " << coldest << " to " << hottest << " C\n"; // They are very handy to go through a map. std::map<std::string, int> goals = {{"Lola", 7}, {"Iker", 12}, {"Sara", 9}}; for (const auto& [player, count] : goals) std::cout << player << " scored " << count << '\n'; return 0;}Output · c++ -std=c++17 main.cpp -o main && ./main
Headphones cost 59.99 euros Valencia: 26 C This week: from 17 to 28 C Iker scored 12 Lola scored 7 Sara scored 9
Key points
std::pair<A, B>holds two values, read withfirstandsecond.std::make_pair(a, b)deduces the types.- A function can return two results in a pair.
auto [a, b] = pair;names each part.for (const auto& [key, value] : map)walks through amap.
Exercise
Write a function that takes a std::vector<int> of marks and returns a std::pair with the average mark (double) and the number of passes (5 or more), and catch the result with a structured binding.