Search code examples
c++functional-programmingrange-v3

range-v3 flatten the vector of struct


Is there any range-v3 way to flatten the vector (or any container) of values in struct? For example,

struct Point{
    double x;
    double y;
};

std::vector<Point> points {
    { 0, 0 },
    { 1, 1 },
    { 2, 2 }
};

I want to make the flattened point vector, which is std::vector { 0, 0, 1, 1, 2, 2 }.


Solution

  • It seems you want:

    auto flatten =
        points | std::ranges::views::transform([](const auto& p){ return std::array{p.x, p.y}; })
               | std::ranges::views::join;