unzip a list of tuples
Asked Answered
C

1

7

Any idea about how to implement this function?

template <class ... Ts> 
auto unzip(const list<tuple<Ts...>> & l)
{
  ...
}

This function would receive a list of tuples and would return a tuple of lists. The first list would contain the elements of get<0>(t), and so on.

I can traverse the items of a tuple and of course traverse the list. But I don't know how declare some such tuple<list<T1>, list<T2> ...>

Any clue or reference?

Centralism answered 20/10, 2016 at 10:18 Comment(0)
U
5

I'd do it like this:

template<typename... Ts, size_t... is>
auto unzip_impl(list<tuple<Ts...>> const& l, std::index_sequence<is...>)
{
    tuple<list<Ts>...> ret;
    for(auto const& el : l) {
        std::initializer_list<int> {
            (std::get<is>(ret).push_back(std::get<is>(el)), 0)...
        };
    }
    return ret;
}

template <class... Ts>
auto unzip(const list<tuple<Ts...>> & l)
{
    return unzip_impl(l, std::index_sequence_for<Ts...>{});
}

live demo

also, more C++17-y version with fold-expressions:

template<typename... Ts, size_t... is>
auto unzip_impl(list<tuple<Ts...>> const& l, std::index_sequence<is...>)
{
    tuple<list<Ts>...> ret;
    for(auto const& el : l) {
        (std::get<is>(ret).push_back(std::get<is>(el)),...);
    }
    return ret;
}

live demo

Unpleasantness answered 20/10, 2016 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.