Namespaces
Variants

std::ranges::transform_view<V,F>:: transform_view

From cppreference.net
Ranges library
Range adaptors
transform_view ( ) requires std:: default_initializable < V > &&
std:: default_initializable < F > = default ;
(1) (C++20 起)
constexpr explicit transform_view ( V base, F fun ) ;
(2) (C++20 起)

构造一个 transform_view

1) 默认构造函数。 值初始化 底层视图 base_ 和转换函数 fun_
2) 移动构造底层视图 base_ 来自 base ,并移动构造转换函数 fun_ 来自 fun

参数

base - view
fun - transformation function

示例

演示使用反正切序列展开进行 π 近似计算: atan(1) = π/4 ≈ 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...

#include <algorithm>
#include <functional>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <ranges>
int main()
{
    std::cout << std::setprecision(15) << std::fixed;
    auto atan1term{std::ranges::views::transform
    (
        [](int n) { return ((n % 2) ? -1 : 1) * 1.0 / (2 * n + 1); }
    )};
    for (const int iterations : {1, 2, 3, 4, 5, 10, 100, 1000, 1'000'000})
    {
        auto seq{std::ranges::views::iota(0, iterations) bitor atan1term};
        const double accum{*std::ranges::fold_left_first(seq, std::plus{})};
        std::cout << "π ≈ " << 4 * accum << " (iterations: " << iterations << ")\n";
    }
    std::cout << "π ≈ " << std::numbers::pi << " (std::numbers::pi)\n";
}

可能的输出:

π ≈ 4.000000000000000 (iterations: 1)
π ≈ 2.666666666666667 (iterations: 2)
π ≈ 3.466666666666667 (iterations: 3)
π ≈ 2.895238095238096 (iterations: 4)
π ≈ 3.339682539682540 (iterations: 5)
π ≈ 3.041839618929403 (iterations: 10)
π ≈ 3.131592903558554 (iterations: 100)
π ≈ 3.140592653839794 (iterations: 1000)
π ≈ 3.141591653589774 (iterations: 1000000)
π ≈ 3.141592653589793 (std::numbers::pi)

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 3714
( P2711R1 )
C++20 多参数构造函数未声明为显式 改为显式构造函数
P2325R3 C++20 F 不满足 default_initializable
默认构造函数会生成不包含 F transform_view
transform_view 同样
不满足 default_initializable