Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - One-liner to iterate nested brace-enclosed lists?

Tags:

c++

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.

like image 731
Huazuo Gao Avatar asked Jun 27 '21 07:06

Huazuo Gao


1 Answers

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)

like image 98
einpoklum Avatar answered Oct 10 '22 06:10

einpoklum