Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unzip a list of tuples

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?

like image 734
lrleon Avatar asked Oct 20 '16 10:10

lrleon


1 Answers

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

like image 123
krzaq Avatar answered Oct 07 '22 01:10

krzaq