Tuesday Coding Tip 03 - Structured bindings

2 5 25
calendar_todayschedule1 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!

837 Points32 Badges2 5 25
Brno, Czech Republiclinkedin.com/in/jakub-neruda
19Posts
10Comments
9Followers
9Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.
Build your own developer journey
Track progress. Share learning. Stay consistent.

2 Comments

0 votes
0
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

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

View all jobs →

Commenters (This Week)

7 comments
4 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!