【问题标题】:In range v3 library, why ranges::copy do not work with output of ranges::views::chunk?在 range v3 库中,为什么 range::copy 不适用于 range::views::chunk 的输出?
【发布时间】:2020-08-25 14:31:10
【问题描述】:

这按预期工作:

#include <range/v3/all.hpp>
#include <iostream>

int main() {
  auto chunklist = ranges::views::ints(1, 13) | ranges::views::chunk(4);
  for (auto rng : chunklist) {
    for (auto elt : rng)
      std::cout << elt << " ";    
    std::cout << std::endl;
  }
}

在屏幕上:

1 2 3 4
5 6 7 8
9 10 11 12

但如果我尝试用 ranges::copy 代替 for 循环,我会收到编译错误

  auto chunklist = ranges::views::ints(1, 13) | ranges::views::chunk(4);
  for (auto rng : chunklist) {
    ranges::copy(rng, std::ostream_iterator<int>{std::cout, " "}); // FAIL
    std::cout << std::endl;
  }

编译错误相当模糊。我不会在这里给出全文,但看起来几乎所有概念都失败了:

note:   constraints not satisfied
...
note: within '...' CPP_concept_bool weakly_incrementable =
...
note: within '...' CPP_concept_bool semiregular =
...
note: within '...' CPP_concept_bool default_constructible =
...
note: within '...' CPP_concept_bool constructible_from =
...
confused by earlier errors, bailing out

我正在使用带有选项的 gcc-9.3:

g++ -fconcepts --std=c++2a chunksimplified.cc

以及来自 github 的 trunk range-v3 库的顶部

我应该如何修改代码以使用显式算法而不是原始循环?

【问题讨论】:

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


    【解决方案1】:

    问题不在于ranges::copy,而在于ranges::views 不能很好地与std::ostream_iterator 配合使用。

    您可以改用ranges::ostream_iterator:

    ranges::copy(rng, ranges::ostream_iterator<int>{std::cout, " "});  
    

    这是一个有效的demo。

    【讨论】:

    • 谢谢它的工作。不知道范围命名空间中的自定义 ostream_iterator。看起来 C++20 只有 std 版本。
    • 老实说,我还没有尝试过任何 c++20 范围的东西。不要期望能够在 c++20 中使用 太多 范围功能。他们会被添加,但这需要时间。
    猜你喜欢
    • 2021-07-04
    • 2020-07-26
    • 2016-06-07
    • 1970-01-01
    • 2021-11-18
    • 2016-05-02
    • 1970-01-01
    • 2021-12-09
    • 2019-08-13
    相关资源
    最近更新 更多