std::ranges::generate
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
呼叫簽名 (Call signature) |
||
template< std::input_or_output_iterator O, std::sentinel_for<O> S, std::copy_constructible F > |
(1) | (C++20 起) |
template< class R, std::copy_constructible F > requires std::invocable<F&> && ranges::output_range<R, std::invoke_result_t<F&>> |
(2) | (C++20 起) |
1) 將函式物件 gen 的連續呼叫結果賦值給範圍
[
first,
last)
中的每個元素。本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
first, last | - | 定義要修改的元素範圍的迭代器-哨兵對 |
r | - | 要修改的元素範圍 |
gen | - | 生成器函式物件 |
[編輯] 返回值
一個與 last 比較相等的輸出迭代器。
[編輯] 複雜度
對 gen() 的呼叫和賦值操作的次數精確地為 ranges::distance(first, last)。
[編輯] 可能的實現
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
[編輯] 參閱
(C++20) |
儲存 N 次應用一個函式的結果 (演算法函式物件) |
(C++20) |
給一個範圍的元素賦某個值 (演算法函式物件) |
(C++20) |
給一定數量的元素賦一個值 (演算法函式物件) |
(C++20) |
對一個範圍的元素應用函式 (演算法函式物件) |
(C++26) |
用來自均勻隨機位生成器的隨機數填充範圍 (演算法函式物件) |
將連續函式呼叫的結果賦給一個範圍中的每個元素 (函式模板) |