Tuesday Coding Tip 03 - Structured bindings

●5 ●27 ●93
calendar_today • schedule1 min read
— Originally published at medium.com

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!

Want more #programming & #cpp deep dives?

Join 5,973+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

Part 3 of 31 in Tuesday Coding Tips

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

Let's play with C++ reflection

Jakub Neruda - Nov 12

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30

Tuesday Coding Tip 31 — Deducing this

Jakub Neruda - Nov 17
chevron_left
2.1k Points • 125 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
42Posts
36Comments
22Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

Commenters (This Week)

1 comment
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!