C++17: Structured Bindings
This is a first post in a series of short articles on new C++17 features. These articles will not contain all little details of the new features being presented, but they give you an idea about what new functionality has been added to C++17.
This first article discusses structured bindings. They allow you to declare multiple variables with a single statement that are initialized with values from a pair, tuple, array, or even a struct.
Let’s look at an example using a tuple. Suppose you have the following tuple consisting of a double, string, and integer (note the use of the user-defined std::string literal s):
auto myTuple = std::make_tuple(1.1, "Hello"s, 42);
Before C++17, if you wanted to decompose this tuple into three separate variables, you could use tie() as follows:
double theDouble; std::string theString; int theInt; std::tie(theDouble, theString, theInt) = myTuple;
That’s 4 lines of code just to decompose the tuple.
C++17 structured bindings allow you to do this with a single line:
auto[theDouble, theString, theInt] = myTuple;
It also works for pairs, and this comes in handy for example when using insert() to insert values into a map. insert() returns a pair with as first element an iterator to the inserted element, and as second element a Boolean that is true if the element was inserted successfully. You can decompose that pair as follows:
std::map<int, int> myMap{ {1, 11}, { 2,22 }, { 3,33 }}; auto[it, success] = myMap.insert({ 4,44 });
If you want to use a range-based for loop to iterate over the elements, you could do it as follows:
for (const auto& element : myMap) { std::cout << element.first << ": " << element.second << std::endl; }
The type of the element variable is a pair containing the key and the value of the elements in the map.
Again, you can use structured bindings to make this shorter and easier to understand:
for (const auto&[key, value] : myMap) { std::cout << key << ": " << value << std::endl; }
Structured bindings are available in Microsoft Visual C++ 2017 since Update 3.