Home > Back-end >  C - Convert any number of nested vector of vector to equivalent vector of span
C - Convert any number of nested vector of vector to equivalent vector of span

Time:12-30

following situation: I work with data that falls into the categories of

std::vector<T> data1;
std::vector<std::vector<T>> data2;
std::vector<std::vector<std::vector<T>>> data3; //etc...

T usually refers to numerical data like double. Sometimes I would like to get the data in a form where the last std::vector is replaced by a std::span<T> pointing to the same data.

std::span<T> data1;
std::vector<std::span<T>> data2;
std::vector<std::vector<std::span<T>>> data3; //etc...

It's not hard to define individual functions for every single level of nesting, but could I somehow also define a single function that could do this automatically for any level of nesting?

CodePudding user response:

You might do:

template <typename T, typename F>
auto transform(std::vector<T>& v, F func)
{
    std::vector<std::decay_t<decltype(func(v[0]))>> res;
    res.reserve(v.size());
    std::transform(v.begin(), v.end(), std::back_inserter(res), func);
    return res;
}

template <typename T>
std::span<T> to_span(std::vector<T>& v)
{
    return v;
}

template <typename T>
auto to_span(std::vector<std::vector<T>>& v)
{
    return transform(v, [](auto& inner){ return to_span(inner); });
}

Demo

  •  Tags:  
  • c
  • Related