Skip to content

Structured binding

Structured binding

Structured binding binds the specified names to subobjects or elements of the initializer.

Like a reference, a structured binding is an alias to an existing object.

1
2
add_executable(structured_binding structured_binding.cpp)
target_compile_features(structured_binding PRIVATE cxx_std_17)

1
2
3
4
std::vector<int> v = {7, 3, 9, 3, 1, 7, 4, 9};
auto [min_value, max_value] = minmax(v);
std::cout << "min_value: " << min_value << '\n';
std::cout << "max_value: " << max_value << '\n';

1
2
3
4
5
6
// `stats` returns `std::tuple<int, double, double, double>`
auto [total, mean, variance, stddev] = stats(v);
std::cout << "total: " << total << '\n';
std::cout << "mean: " << mean << '\n';
std::cout << "variance: " << variance << '\n';
std::cout << "stddev: " << stddev << '\n';

1
2
3
4
5
struct Foo {
    int i;
    char c;
    double d;
};

1
2
3
4
5
Foo f{1, 'a', 2.3};
auto [i, c, d] = f;
std::cout << "f.i: " << i << '\n';
std::cout << "f.c: " << c << '\n';
std::cout << "f.d: " << d << '\n';

1
2
3
4
auto &[i2, c2, d2] = f;
std::cout << "i2: " << i2 << '\n';
std::cout << "c2: " << c2 << '\n';
std::cout << "d2: " << d2 << '\n';

1
2
3
4
int a[2] = {1, 2};
auto [x, y] = a;
std::cout << "x: " << x << '\n';
std::cout << "y: " << y << '\n';

1
2
3
4
5
6
7
8
9
std::map<std::string, int> my_map = {
    {"hello", 1},
    {"world", 2},
    {"it's", 3},
    {"me", 4},
};
for (auto &&[key, value] : my_map) {
    std::cout << "key=" << key << " value=" << value << '\n';
}

1
2
3
4
5
6
7
if (auto [iter, success] = my_map.insert(std::make_pair("Bye", 5)); success) {
    auto &[key, value] = *iter;
    std::cout << "insert is successful. The value is " << quoted(key) << '\n';
} else {
    auto &[key, value] = *iter;
    std::cout << "The value " << quoted(key) << " already exists in the set\n";
}

1
2
3
4
5
std::pair<int, int> minmax(std::vector<int> &v) {
    // unpack tuple of iterators with min and max
    auto [min_iter, max_iter] = std::minmax_element(v.begin(), v.end());
    return std::make_pair(*min_iter, *max_iter);
}

Share Snippets