Search code examples
c++boostrange-v3boost-range

How to generate a view of pairs from an array?


I have a C array of ints, and its size, i.e. int* arr, unsigned size. I want to have something like a view from it, which will have pairs of ints as elements.

To clarify, the task is: I receive an array like [1,2,3,4] and I want a view, which will be something like [(1,2),(3,4)].

Is there any convenient way to transform array in such a way via boost, or maybe, ranges (std::ranges, or range-v3)?


Solution

  • With range v3, you may create a range of range of size 2 with ranges::v3::view::chunk(2)

    or create a tuple:

    auto r = ranges::view::counted(p, size);
    auto even = r | ranges::view::stride(2);
    auto odd = r | ranges::view::drop(1) | ranges::view::stride(2);
    auto pairs = ranges::view::zip(even, odd);
    

    Demo