Home > OS >  Store multiple std arrays of variable size
Store multiple std arrays of variable size

Time:09-27

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?

CodePudding user response:

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)
{
    ...
}

CodePudding user response:

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.

CodePudding user response:

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.

  • Related