cpp / intermediate
Snippet
Structured Bindings for Array Iteration
Structured bindings allow you to unpack objects into multiple variables in a single step. When used in a range-based for loop over an array of structs, it makes the code much more readable by giving meaningful names to individual members immediately.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>struct DataPoint {int id;double value;};int main() {DataPoint measurements[] = {{1, 98.6}, {2, 101.2}, {3, 99.5}};// Unpacking struct members directly in the loopfor (const auto& [currentId, currentVal] : measurements) {std::cout << "ID: " << currentId << " | Val: " << currentVal << std::endl;}return 0;}
Breakdown
1
const auto& [currentId, currentVal]
Decomposes the struct into two alias variables linked to the actual elements.
2
for (... : measurements)
Iterates through each element of the measurements array.