Sign up for the KDAB Newsletter
Stay on top of the latest news, publications, events and more.
Go to Sign-up
Find what you need - explore our website and developer resources
23 March 2023
Iterating over the values of a QMap or QHash traditionally happened by iterating over the key and then looking up the value using that key. Besides that, this requires an additional lookup, it is also a bit clumsy.
A much more elegant solution to the problem is structured bindings - a feature introduced in C++17. To use this out of the box, you need Qt 6.4 but this episode shows how you relatively easily can enable it for older Qt versions too.
There is commentary edition of this video with Giuseppe D'Angelo as host. You can find it here:
https://www.youtube.com/watch?v=xGNkh9azkBM
0:00 Introduction
0:42 Returning two values from a class in the old days
1:48 Now returning a pair
2:12 Same thing with std:(Zunge)air
3:14 Now with structured bindings
3:52 Structured bindings with QPair
4:25 When are structured bindings interesting?
5:10 Iterating over a std::map using structured bindings
6:01 QMap/QHash and structured bindings
7:34 constKeyValueBegin()
8:05 Class asRange
10:08 Why not "const Container& container" - a discussion of lifetime
13:00 Adding an rvalue version
14:25 Implementing your own structured unpacking
Links:
* https://www.kdab.com/qt-range-based-for-loops-and-structured-bindings
* https://en.cppreference.com/w/cpp/language/structured_binding
The example code showcased in this video is available here: https://github.com/KDAB/kdabtv/tree/master/Qt-Widgets-and-more/ranges
All QML tips and tricks videos : https://www.youtube.com/playlist?list=PL6CJYn40gN6jWHP5krsQrVGyYtKh3A3be
All Qt Widgets and more videos:
https://www.youtube.com/playlist?list=PL6CJYn40gN6gf-G-o6syFwGrtq3kItEqI