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 lists (each list can contain a different type) and return a list of tuples.
It seems like this should work
@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.