auto and structured bindings
auto lets the compiler infer a variable's type from its initialiser. It shines for long iterator and lambda types and keeps code correct when a function's return type changes. Structured bindings (C++17) unpack a pair, tuple, array or struct into named variables in one line: auto [name, qty] = entry;. Combined with range-for over a map, they replace it->first and it->second with names that say what they are.
#include <iostream>
#include <map>
#include <string>
#include <tuple>
struct Stats { int min; int max; double mean; };
Stats summarize(int a, int b, int c) {
int lo = std::min({a, b, c});
int hi = std::max({a, b, c});
return {lo, hi, (a + b + c) / 3.0};
}
std::tuple<std::string, int, bool> lookup() { return {"widget", 12, true}; }
int main() {
auto [lo, hi, mean] = summarize(4, 9, 2);
std::cout << lo << ' ' << hi << ' ' << mean << '\n';
auto [name, qty, inStock] = lookup();
std::cout << name << " x" << qty << (inStock ? " in stock" : " sold out") << '\n';
std::map<std::string, int> stock{{"apple", 3}, {"fig", 0}};
for (const auto& [item, count] : stock) std::cout << item << ':' << count << ' ';
std::cout << '\n';
if (auto [it, inserted] = stock.insert({"kiwi", 7}); inserted) // if with initializer
std::cout << "added " << it->first << '\n';
}2 9 5
widget x12 in stock
apple:3 fig:0
added kiwiconst auto& in the loop binds to each map entry without copying it. map::insert returns a pair of an iterator and a bool, which unpacks naturally.
Structured binding count does not match
#include <tuple>
int main() {
std::tuple<int, double, char> t{1, 2.5, 'x'};
auto [a, b] = t;
return a;
}main.cpp:5:10: error: type 'std::tuple<int, double, char>' decomposes into 3 elements, but only 2 names were provided
5 | auto [a, b] = t;
| ^
1 error generated.A structured binding must name every element. There is no way to skip one by leaving it out.
Name all three, and mark the ones you do not use with [[maybe_unused]] (or a name like _unused); or use std::get<0>(t) when you only need one element.
#include <tuple>
int main() {
std::tuple<int, double, char> t{1, 2.5, 'x'};
[[maybe_unused]] auto [a, b, c] = t;
return a;
}