How to generate a view of pairs from an array?
Asked Answered
C

2

2

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)?

Campney answered 21/12, 2018 at 9:52 Comment(1)
ranges::v3::view::chunk(2) creates a range of range(of size 2).Lafave
L
4

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

Lafave answered 21/12, 2018 at 10:55 Comment(0)
M
2

You can use range-v3, it has span to view a raw array, and view::chunk to group adjacent elements:

#include <iostream>
#include <range/v3/view/chunk.hpp>
#include <range/v3/span.hpp>
#include <range/v3/algorithm/for_each.hpp>

namespace view = ranges::view;

int main() {
    int vec[] = { 1, 2, 3, 4, 5, 6 };
    ranges::span<int> s(vec, sizeof(vec)/sizeof(vec[0]));

    ranges::for_each(s | view::chunk(2), [] (auto chunk) {
                std::pair pr{chunk.at(0), chunk.at(1)};

                std::cout << pr.first << " " << pr.second << "\n";
            });
}

Live Demo

Magocsi answered 21/12, 2018 at 10:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.