3

I have different std::arrays with variable sizes, e.g.

std::array<int, 5> array_one;
std::array<int, 8> array_two;
std::array<int, 2> array_three;

The primary type is always the same (int in this example).

Now I have to iterate over all those arrays and in order to do that with as little code as possible, I thought I would store them in e.g. one array and use it to access each array individually.

Pseudocode:

std::array array_wrapper = { array_one, array_two, array_three };

But that will not work as each array has a different size.

Is there any storage type I can use to "collect" all arrays to iterate over them individually afterwards?

2
  • 2
    You may use a std::tuple<...> for this Commented Sep 26, 2021 at 10:26
  • Not a huge fan of tuple iterations since c++20 does not yet contain expansion statements, but that if that is my only option, I guess I'll have to bite the bullet Commented Sep 26, 2021 at 10:40

3 Answers 3

11

In case you just need to iterate, not to store arrays together, use std::span

std::span<int> span[] = {array_one, array_two, array_three};

You may also flatten the views with std::views::join

for(int &i : span | std::views::join)
{
    ...
}

If arrays are constant, then

std::span<int const> span[] = {array_one, array_two, array_three};
for(int const i : span | std::views::join)
{
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

4

I'd suggest using std::tuple:

int main() {
    auto array_one = std::array<int, 5>();
    auto array_two = std::array<int, 8>();
    auto array_three = std::array<int, 2>();

    auto array_wrapper = std::make_tuple(array_one, array_two, array_three);

    auto print_array = [](const auto& array) {
        for (const auto& element : array) {
            std::cout << element << ' ';
        }
        std::cout << '\n';
    };
    std::apply(
            [print_array](const auto& ... elements) {
                (print_array(elements), ...);
            },
            array_wrapper
    );
}

Here we simply wrap your std::arrays in a std::tuple and apply print_array to every element of the wrapper, printing every array in a separate row.

Comments

1

There's also boost::hana::make_tuple:

#include <array>
#include <boost/hana/tuple.hpp>

std::array<int, 5> array_one;
std::array<int, 8> array_two;
std::array<int, 2> array_three;

auto t = boost::hana::make_tuple(array_one, array_two, array_three);

And I remember Boost.Hana author's Louis Dionne say in a video recording of a talk that he didn't like std::tuple because it was not good enough, so he implemented boost::hana::tuple.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.