Tuesday Coding Tip 03 - Structured bindings

posted Originally published at medium.com 1 min read

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


Since C++17, we can use “structured bindings”. These allow you to perform tuple, array, or even structure unpacking. Such unpacking is commonly helpful when iterating over maps, so you don’t have to define an alias for key and value manually. It is equally useful when a function returns a tuple.

// Iterating over key-value pairs
auto myMap = std::unordered_map<std::string, int>{ /* ... */ };
for (auto&& [key, value] : myMap)
{ /* ... */ }

// Tuple unpacking
auto&& [index, quantity, name] = std::tuple{10, 30, "a"};

// Struct member aliasing
struct S {
    int veryLongAndDescriptiveName;
    std::string anotherVeryWordyName;
};

auto&& [index2, name2] = S{}; // s is of type S

// Array unpacking
auto&& [first, second, third] = std::array{1, 2, 3};

Unpacking struct members and arrays is just a cherry on top. You won’t use it much, but it is there should you ever need it!

2 Comments

0 votes
0

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelskiverified - Apr 23
chevron_left

Related Jobs

Commenters (This Week)

3 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!