In Python we can do
for i, j in [(0, 0), (0, 1), (1, 0), (1, 1)]:
...
Is there something similar in C++?
In the non-nested case there is
for (auto i : {0, 1});
but extending to nested lists
for (auto [i, j] : {{0, 0}, {0, 1}, {1, 0}, {1, 1}});
doesn't compile.
This works:
#include <initializer_list>
#include <utility>
void foo() {
for (auto [i, j] : std::initializer_list<std::pair<int,int>> {
{0, 0}, {0, 1}, {1, 0}, {1, 1}}
);
}
and note you have to include the two headers.
You can also use this shorter version:
#include <initializer_list>
#include <utility>
void bar() {
for (auto [i, j] : {std::pair{0, 0}, {0, 1}, {1, 0}, {1, 1}});
}
and again - you need to include both of these headers.
(See it all on Godbolt)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With