std::ranges::generate
来自cppreference.com
| 在标头 <algorithm> 定义
|
||
| 调用签名 |
||
| |
(1) | (C++20 起) |
| |
(2) | (C++20 起) |
1) 对范围
[first, last) 中的每个元素赋值连续调用函数对象 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
