【问题标题】:What is the correct way of filtering the output of group_by with Range-v3?使用 Range-v3 过滤 group_by 输出的正确方法是什么?
【发布时间】:2020-11-21 07:22:22
【问题描述】:

以下代码无法编译,因为x 无法与std::vector<int> 进行比较,因为x 是由 Range-v3 处理的更复杂的结构(这很好,因为它很懒,不像std::vector<int>) .

我如何编写过滤 lambda 来应对这种情况,可能不会强制将 x 不必要地转换为 std::vector<int>

#include <range/v3/view/filter.hpp>
#include <range/v3/view/group_by.hpp>
#include <vector>

int main() {
    std::vector<int> v{1,2,3,4,5};
    auto w = v
        | ranges::views::group_by([](auto const& c1, auto const& c2){ return c1 == 3 && c2 == 4; })
        | ranges::views::filter([](auto const& x){ return x != std::vector<int>{3,4}; });
}

【问题讨论】:

    标签: c++ c++17 range-v3


    【解决方案1】:

    您可能仍将视图转换为矢量:

     | ranges::views::filter([](auto const& x){ return (x | ranges::to_vector) != std::vector<int>{3,4}; });
    

    Demo

    或不转换为矢量,使用ranges::equal:

    ranges::view::filter([](auto const& x){ return !ranges::equal(x, std::vector<int>{3,4}); })
    

    Demo

    【讨论】:

    • 抱歉回复晚了,但这正是我要找的!
    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 2021-07-04
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2013-07-20
    相关资源
    最近更新 更多