1

Is there a way to write the following code nicely in C++20 without using std::array

for (const auto [x, y, z] : {std::array{1, 2, 3},
                                          {47, 48, 49},
                                          {100, 200, 300}})
{

}

By nicely I mean something that is more readable and less spammy, e.g. tuple instead of array is not really an improvement.

NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
  • 2
    Looks good to me. What's supposed to be spammy about this? The initializer list needs to know the type of its elements, so this makes absolute sense. The best you can do is pull this out of the loop and assign it to a variable instead. – Jan Schultke Aug 28 '20 at 09:56
  • I'm voting to close this as opinion based. – super Aug 28 '20 at 10:05

1 Answers1

2

By nicely I mean something that is more readable and less spammy

I guess it's arguable whether this is an improvement or not (and this very statement begs the questions whether the OP can only be answered in an opinion based manner?), but as it makes use of new C++20 feature it may prove useful for readers of this question nonetheless.

You could combine structured bindings with range-based for loop initialization statements separate the initialization of the matrix object with that of the structured bindings loop over its elements; e.g.:

for (const int matrix[3][3] = 
        {{1, 2, 3}, {47, 48, 49}, {100, 200, 300}};
     const auto [x, y, z] : matrix)
{
        // ...
}

for (const auto matrix = 
        {std::array{1, 2, 3}, {47, 48, 49}, {100, 200, 300}};
     const auto [x, y, z] : matrix)
{
        // ...
}

for (typedef std::array<int, 3> Row;
     const auto [x, y, z] : {Row{1, 2, 3}, {47, 48, 49}, {100, 200, 300}})
{
        // ...
}

where the final example makes use of the fact that typedef declarations are init-statements (where alias-declarations are not).

dfrib
  • 70,367
  • 12
  • 127
  • 192