views::iota 和 ranges::iota_view – “表达式等价”,为什么两者都存在?

huangapple go评论65阅读模式
英文:

views::iota vs ranges::iota_view - "expression equivalent" so why both exist?

问题

#include <iostream>
#include <ranges>

int main()
{
    for (int num: std::ranges::views::iota(0,5)) {
        std::cout << num << 'n';
    }
    
    for (int i : std::ranges::iota_view{55, 65}) {
        std::cout << i << '\n';
    }
}

CPP Reference
> 2) views::iota(e)views::iota(e, f)iota_view(e)iota_view(e, f) 在任何适当的子表达式 ef 上都是表达式等效的

是否有使用一个而不是另一个的理由?

如果没有,它们都存在的原因是什么,因为它们都是在 C++20 中引入的吗?


<details>
<summary>英文:</summary>

    #include &lt;iostream&gt;
    #include &lt;ranges&gt;

    int main()
    {
        for (int num: std::ranges::views::iota(0,5)) {
        	std::cout &lt;&lt; num &lt;&lt; &#39;n&#39;;
        }
        
        for (int i : std::ranges::iota_view{55, 65}) {
            std::cout &lt;&lt; i &lt;&lt; &#39;\n&#39;;
        }
    }

[CPP Reference][1]
&gt; 2) `views::iota(e)` and `views::iota(e, f)` are **expression-equivalent** to
&gt; `iota_view(e)` and `iota_view(e, f)` respectively for any suitable
&gt; subexpressions `e` and `f`.

Is there any reason to use one vs the other?

And if not, why do they both exist since they were both introduced in C++20?

[1]: https://en.cppreference.com/w/cpp/ranges/iota_view


</details>


# 答案1
**得分**: 6

`std::ranges::iota_view` 是一种表现得像生成其元素的视图的类型。它必须以某种方式可构造。

`std::views::iota` 是一个辅助自定义点对象,遵循一种模式,当使用时可以产生更高性能/正确的结果。最终它将返回 `std::ranges::iota_view`。所谓的模式是使用 `views::something` 而不是 `ranges::something_view`。

当您嵌套更多适配器时,使用后者可能会产生更好的结果(主要是在编译时)。

一般来说,[更倾向于使用 `views::meow`](https://brevzin.github.io/c++/2023/03/14/prefer-views-meow/)。

<details>
<summary>英文:</summary>

`std::ranges::iota_view` is the type that behaves like a view that generates its elements ad hoc. It must be somehow constructible.

`std::views::iota` is a helper customization point object that follows a pattern which can yield more performant / correct results when used. It will ultimately return `std::ranges::iota_view`. Said pattern is the usage of `views::something` rather than `ranges::something_view`.

When you nest more adaptors together, using the latter may turn out to produce better results (mainly in terms of compile-time).

In general, [prefer `views::meow`](https://brevzin.github.io/c++/2023/03/14/prefer-views-meow/).



</details>



huangapple
  • 本文由 发表于 2023年7月14日 03:20:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76682621.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定