Unzip the tuple list

Any idea on how to implement this feature?

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

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

I can traverse the elements of the tuple and, of course, navigate the list. But I do not know how to declare some such tuple<list<T1>, list<T2> ...>

Any hint or link?

+6
source share
1 answer

I would 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 demonstration

also, more C ++ 17th 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 demonstration

+4
source

Source: https://habr.com/ru/post/1011503/


All Articles