You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用zip_view结合filter_view时出现C++编译错误求助

问题:zip视图结合filter时编译失败

尝试将两个vector通过ranges::views::zip打包后,使用ranges::views::filter进行过滤时出现编译错误。

原代码

#include <range/v3/all.hpp>

int main()
{
    std::vector v1 = {0, 1, 2, 3, 4};
    std::vector v2 = {'a', 'b', 'c', 'd', 'e'};

    auto pred = [](auto& p) { return (p.first != 0); };

    auto x = ranges::views::zip(v1, v2);
    auto y = x | ranges::views::filter(pred);
}

编译错误信息(翻译后)

<source>: 在函数'int main()'中:
<source>:15:16: 错误: 无法匹配'operator|'(操作数类型分别为'ranges::zip_view<ranges::ref_view<std::vector<int, std::allocator<int> > >, ranges::ref_view<std::vector<char, std::allocator<char> > > >'和'ranges::views::view_closure<ranges::detail::bind_back_fn_<ranges::views::filter_base_fn, main()::<lambda(auto:28&)> > >')
   15 |     auto y = x | ranges::views::filter(pred);
      |              ~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
      |              |                        |
      |              |                        ranges::views::view_closure<ranges::detail::bind_back_fn_<ranges::views::filter_base_fn, main()::<lambda(auto:28&)> > >
      |              ranges::zip_view<ranges::ref_view<std::vector<int, std::allocator<int> > >, ranges::ref_view<std::vector<char, std::allocator<char> > > >
包含自/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/regex:40,
                 自/opt/compiler-explorer/libs/rangesv3/0.12.0/include/range/v3/view/tokenize.hpp:18,
                 自/opt/compiler-explorer/libs/rangesv3/0.12.0/include/range/v3/view.hpp:81,
                 自/opt/compiler-explorer/libs/rangesv3/0.12.0/include/range/v3/all.hpp:25,
                 自<source>:4:

解决方案

问题出在lambda表达式中使用了p.first访问zip后的元素——range-v3的zip_view返回的元素是类tuple的对象,而非std::pair,因此没有.first成员。

可以通过两种方式修正:

方式1:使用结构化绑定

修改lambda参数,直接解构zip后的元素:

auto pred = [](auto&& p) {
    auto [num, ch] = p;
    return num != 0;
};

方式2:使用ranges::get访问元素

通过索引获取tuple中的第一个元素:

auto pred = [](auto& p) {
    return ranges::get<0>(p) != 0;
};

修正后的完整代码示例:

#include <range/v3/all.hpp>

int main()
{
    std::vector v1 = {0, 1, 2, 3, 4};
    std::vector v2 = {'a', 'b', 'c', 'd', 'e'};

    auto pred = [](auto&& p) {
        auto [num, ch] = p;
        return num != 0;
    };

    auto x = ranges::views::zip(v1, v2);
    auto y = x | ranges::views::filter(pred);
}

内容的提问来源于stack exchange,提问作者Shakti Malik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 17:43:23