◐ Shell
clean mode source ↗

std::ranges::generate - cppreference.com

来自cppreference.com

在标头 <algorithm> 定义

调用签名

template< std::input_or_output_iterator O, std::sentinel_for<O> S,
          std::copy_constructible F >
requires std::invocable<F&> && std::indirectly_writable<O, std::invoke_result_t<F&>>
constexpr O
    generate( O first, S last, F gen );
(1) (C++20 起)
template< class R, std::copy_constructible F >
requires std::invocable<F&> && ranges::output_range<R, std::invoke_result_t<F&>>
constexpr ranges::borrowed_iterator_t<R>
    generate( R&& r, F gen );
(2) (C++20 起)

1) 对范围 [firstlast) 中的每个元素赋值连续调用函数对象 gen 的结果。

2)(1),但以 r 为范围,如同以 ranges::begin(r)first 并以 ranges::end(r)last

此页面上描述的函数式实体是算法函数对象(非正式地称为 niebloid),即:

参数

first, last - 要修改的元素范围的迭代器-哨位对
r - 要修改的元素范围
gen - 生成器函数对象

返回值

等于 last 的输出迭代器。

复杂度

准确 ranges::distance(first, last) 次调用 gen() 以及赋值。

可能的实现

struct generate_fn
{
    template<std::input_or_output_iterator O, std::sentinel_for<O> S,
             std::copy_constructible F>
    requires std::invocable<F&> && std::indirectly_writable<O, std::invoke_result_t<F&>>
    constexpr O operator()(O first, S last, F gen) const
    {
        for (; first != last; *first = std::invoke(gen), ++first)
        {}
        return first;
    }

    template<class R, std::copy_constructible F>
    requires std::invocable<F&> && ranges::output_range<R, std::invoke_result_t<F&>>
    constexpr ranges::borrowed_iterator_t<R> operator()(R&& r, F gen) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::move(gen));
    }
};

inline constexpr generate_fn generate {};

示例

#include <algorithm>
#include <array>
#include <iostream>
#include <random>
#include <string_view>

auto dice()
{
    static std::uniform_int_distribution<int> distr{1, 6};
    static std::random_device device;
    static std::mt19937 engine {device()};
    return distr(engine);
}

void iota(auto& r, int init)
{
    std::ranges::generate(r, [init]() mutable { return init++; });
}

void print(std::string_view comment, const auto& v)
{
    for (std::cout << comment; int i : v)
        std::cout << i << ' ';
    std::cout << '\n';
}

int main()
{
    std::array<int, 8> v;

    std::ranges::generate(v.begin(), v.end(), dice);
    print("dice: ", v);
    std::ranges::generate(v, dice);
    print("dice: ", v);

    iota(v, 1);
    print("iota: ", v);
}

可能的输出:

dice: 4 3 1 6 6 4 5 5
dice: 4 2 5 3 6 2 6 2
iota: 1 2 3 4 5 6 7 8

参阅

保存 N 次函数应用的结果
(算法函数对象) [编辑]
赋给定值到范围中元素
(算法函数对象) [编辑]
赋给定值到若干元素
(算法函数对象) [编辑]
应用函数到元素范围
(算法函数对象) [编辑]
用来自均匀随机位发生器的随机数填充范围
(算法函数对象) [编辑]
赋连续函数调用结果到范围中所有元素
(函数模板) [编辑]