C++ zip variadic templates

c++, c++11, iterator, tuples, variadic-templates

Solution

It seems like this should work

std::list<std::tuple<>> simple_zip() {
  return {};
}

template <typename ...T>
std::list<std::tuple<T...>> simple_zip(std::list<T>... lst)
{
  std::list<std::tuple<T...>>  result;
  for (int i = 0, e = std::min({lst.size()...}); i != e; i++) {
    result.emplace_back(std::move(lst.front())...);
    [](...){} ((lst.pop_front(), 0)...);
  }
  return result;
}

@Potatoswatter had the good (IMO) remark that this may copy more than needed when the lists are of different size, and that using only iterators will be better since pop_front does more than actually needed. I think the following "fixes" the iterator one at the cost of more code.

template <typename ...T>
std::list<std::tuple<T...>> simple_zip(std::list<T>... lst)
{
  std::list<std::tuple<T...>>  result;
  struct {
    void operator()(std::list<std::tuple<T...>> &t, int c,
             typename std::list<T>::iterator ...it) {
      if(c == 0) return;
      t.emplace_back(std::move(*it++)...);
      (*this)(t, c-1, it...);
    }
  } zip;
  zip(result, std::min({lst.size()...}), lst.begin()...);
  return result;
}

std::list<std::tuple<>> simple_zip() {
  return {};
}

Problem

Here is a simple two-container zip function in C++: ``` template <typename A, typename B> std::list<std::pair<A, B> > simple_zip(const std::list<A> & lhs, const std::list<B> & rhs) { std::list<std::pair<A, B> > result; for (std::pair<typename std::list<A>::const_iterator, typename std::list<B>::const_iterator> iter = std::pair<typename std::list<A>::const_iterator, typename std::list<B>::const_iterator>(lhs.cbegin(), rhs.cbegin()); iter.first != lhs.end() && iter.second != rhs.end(); ++iter.first, ++iter.second) { result.push_back( std::pair<A, B>(*iter.first, *iter.second) ); } return result; } ``` How would I extend this to an arbitrary number of containers with variadic templates? I'd like `general_zip` to accept a `tuple` of `list`s (each list can contain a different type) and return a `list` of `tuple`s.

Original source