关于 https://en.cppreference.com/w/cpp/ranges , std::views::counted 列在 range adapters 部分。但是,它没有被标记为范围适配器对象。
我想这就是为什么我不能像这样使用管道运算符来编写:
std::vector<size_t> vec = {1, 2, 3, 4, 5};
auto view = vec | std::ranges::counted(... ; // does not compile
我的问题是:
- 什么是 std::ranges::counted? 为什么它列在范围适配器部分?
- 有哪些用例?与使用 take 和 drop 相比有什么优势?
最佳答案
Cppreference遵循C++20标准的组织。并将 views::counted
放入 the "Range Adaptors" section .尽管标准说:
These adaptors can be chained to create pipelines of range transformations that evaluate lazily as the resulting view is iterated.
views::counted
的行为 并非如此。事实上,该部分中的大多数其他元素都说它们的自定义点“表示 range adaptor object ”(描述管道功能),但是 views::counted
does not .
不清楚他们为什么将它放在那个部分,但它本身就是一种有用的类型。这实际上只是一种表达 subrange(it, it + n)
的有效方式。它的高效在于它实际上不会将迭代器递增 n
。
与 take_view
相比,它的优势在于 take_view
在一个范围内运行,而所有 counted
需要的是一个迭代器。主要区别在于 counted
假设 有 n
个有效的迭代器位置(如果不是这种情况将给出 UB),而 take_view
没有。 take_view
将为您提供 最多 n
个对象,但如果范围小于该范围(由哨兵定义),则不会尝试迭代超过范围的末尾。
关于c++ - 什么是 std::views::counted?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74657339/