Home >Backend Development >C++ >How Can I Achieve Python's `zip` Functionality with Multiple Ranges in C 11?

How Can I Achieve Python's `zip` Functionality with Multiple Ranges in C 11?

Barbara Streisand
Barbara StreisandOriginal
2024-12-13 17:18:11474browse

How Can I Achieve Python's `zip` Functionality with Multiple Ranges in C  11?

Sequence-zip Function for C 11?

The range-based for-loop in C 11 offers significant improvements in code readability and succinctness. It allows you to iterate over a range of elements using a simplified syntax, as seen in:

for (auto x : Y) {}

However, this syntax does not directly extend to looping over multiple concurrent ranges, like Python's zip function.

Boost Solution

Prior to C 11, the Boost library provided two methods to emulate Python's zip functionality:

Boost.Range.Combine:

#include <boost/range/combine.hpp>

std::vector<int> a {4, 5, 6};
double b[] = {7, 8, 9};
std::list<std::string> c {"a", "b", "c"};

for (auto tup : boost::combine(a, b, c, a)) {
    int x, w;
    double y;
    std::string z;
    boost::tie(x, y, z, w) = tup;
    printf("%d %g %s %d\n", x, y, z.c_str(), w);
}

Boost.Iterator.ZipIterator:

#include <boost/iterator/zip_iterator.hpp>
#include <boost/range.hpp>

template <typename... T>
auto zip(T&&... containers) -> boost::iterator_range<boost::zip_iterator<decltype(boost::make_tuple(std::begin(containers)...))>>
{
    auto zip_begin = boost::make_zip_iterator(boost::make_tuple(std::begin(containers)...));
    auto zip_end = boost::make_zip_iterator(boost::make_tuple(std::end(containers)...));
    return boost::make_iterator_range(zip_begin, zip_end);
}

std::vector<int> a {4, 5, 6};
double b[] = {7, 8, 9};
std::list<std::string> c {"a", "b", "c"};

for (auto tup : zip(a, b, c, a)) {
    int x, w;
    double y;
    std::string z;
    std::tie(x, y, z, w) = tup;
    printf("%d %g %s %d\n", x, y, z.c_str(), w);
}

The above is the detailed content of How Can I Achieve Python's `zip` Functionality with Multiple Ranges in C 11?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn