带有自动和结构化绑定的Range V3 zip

问题描述 投票:0回答:1

我希望能够使用C ++范围通过压缩容器而不是显式地索引它们来帮助简化代码逻辑。我可以将其与冗长的lambda参数一起使用,但我想尝试通过添加更多auto使其更简​​单/可概括。

const int n = ...;
std::vector<float> a(n), b(n), c(n);

...initialize a and b...

// This works
ranges::for_each(
    ranges::views::zip(a, b, c),
    [](const std::tuple<float&, float&, float&>& v)
    {
        const auto& [a, b, c] = v;
        c = a + b; 
        std::cout << typeid(v).name(); // NSt3__15tupleIJRfS1_S1_EEE
    }
);

// This fails
ranges::for_each(
    ranges::views::zip(a, b, c),
    [](const auto& v)
    {
        const auto& [a, b, c] = v;
        // c = a + b; 
        std::cout << typeid(v).name(); // N6ranges12common_tupleIJRfS1_S1_EEE
    }
);

Ranges-v3文档说以下:

views::zip

给出N

范围,返回一个新范围,其中Mth元素是对所有N范围的Mth元素调用make_tuple的结果。

[这使我认为我应该能够将ranges::common_tuple转换为std::tuple,然后我查看了公共成员并发现:]]

std::tuple< Ts... > const & base() const noexcept

但是无论如何也不能编译:

const auto& [a, b, c] = v.base();
// error: no member named 'base' in 'std::__1::tuple<float, float, float>'

但是当我打印typeid(v)时,它不是std::tuple;它是ranges::common_tuple。我想在这里使用auto类型推导做些什么吗? (如果需要的话,请使用clang编译器)

我希望能够使用C ++范围通过压缩容器而不是显式地索引它们来帮助简化代码逻辑。我可以将其与冗长的lambda参数一起使用,但是我...

c++ tuples c++17 auto structured-bindings
1个回答
0
投票

简短的答案是:如果您实际上不需要const,请不要使用const。您想要修改某些内容,为什么要选择const?效果很好:

ranges::for_each(
    ranges::views::zip(a, b, c),
    [](auto&& v)
    {
        auto&& [a, b, c] = v;
        c = a + b; 
    }
);
© www.soinside.com 2019 - 2024. All rights reserved.