C++17’s Structured Bindings

C++17 provides a really cool feature that allows us to unpack / decompose structures into their constituent values. This combines some syntactic sugar and automatic type deductaion to create structured bindings. The below code provides some example use cases:

#include <iostream>
#include <vector>

using namespace std;

struct Element {
    Element(int _a, char _b) :
        a(_a),
        b(_b) {}
    int a = 0;
    char b = 'b';
};

int main(int argc, char* arg[]) {

    vector<Element> elements = { 
        {1, 'a'},
        {2, 'b'},
        {3, 'c'},
        {4, 'd'}
    };

    for(auto const &[a, b] : elements) {
        cout << a << " " << b << endl;
    }

    return 0;
}

This produces the following output (when built with –std=c++17):

$ ./a.out
1 a
2 b
3 c
4 d
#include <iostream>
#include <vector>

using namespace std;

struct Element {
    Element(int _a, char _b) :
        a(_a),
        b(_b) {}
    int a = 0;
    char b = 'b';
};

int main(int argc, char* arg[]) {

    vector<Element> elements = { 
        {1, 'a'},
        {2, 'b'},
        {3, 'c'},
        {4, 'd'}
    };

    for(auto const &[a, b] : elements) {
        cout << a << " " << b << endl;
    }

    return 0;
}
C++17’s Structured Bindings

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top