Tuesday Coding Tip 03 - Structured bindings

●5 ●35 ●98
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 6,118+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

Part 3 of 33 in Tuesday Coding Tips

2 Comments

0 votes
0

More Posts

Tuesday Coding Tip 33 — Imported CMake targets

Jakub Neruda - Dec 1

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
chevron_left
2.2k Points • 138 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
47Posts
40Comments
25Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Commenters (This Week)

3 comments
2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!