std::ranges::generate_n
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
呼叫簽名 (Call signature) |
||
template< std::input_or_output_iterator O, std::copy_constructible F > requires std::invocable<F&> && std::indirectly_writable<O, std::invoke_result_t<F&>> |
(C++20 起) | |
將函式物件 gen 的連續呼叫結果賦值給範圍 [
first,
first + n)
中的每個元素,如果 0 < n。否則不執行任何操作。
本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
first | - | 要修改的元素範圍的起始 |
n | - | 要修改的元素數量 |
gen | - | 生成器函式物件。 |
[編輯] 返回值
如果 0 < count,則返回已賦值的最後一個元素之後一個位置的迭代器,否則返回 first。
[編輯] 複雜度
精確地呼叫 gen() n 次並進行賦值。
[編輯] 可能實現
struct generate_n_fn { template<std::input_or_output_iterator O, std::copy_constructible F> requires std::invocable<F&> && std::indirectly_writable<O, std::invoke_result_t<F&>> constexpr O operator()(O first, std::iter_difference_t<O> n, F gen) const { for (; n-- > 0; *first = std::invoke(gen), ++first) {} return first; } }; inline constexpr generate_n_fn generate_n {}; |
[編輯] 示例
執行此程式碼
#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 engine; static std::mt19937 noise {engine()}; return distr(noise); } void print(const auto& v, std::string_view comment) { for (int i : v) std::cout << i << ' '; std::cout << '(' << comment << ")\n"; } int main() { std::array<int, 8> v; std::ranges::generate_n(v.begin(), v.size(), dice); print(v, "dice"); std::ranges::generate_n(v.begin(), v.size(), [n {0}] mutable { return n++; }); // same effect as std::iota(v.begin(), v.end(), 0); print(v, "iota"); }
可能的輸出
5 5 2 2 6 6 3 5 (dice) 0 1 2 3 4 5 6 7 (iota)
[編輯] 參閱
(C++20) |
將一個函式的結果儲存在一個範圍中 (演算法函式物件) |
(C++26) |
用來自均勻隨機位生成器的隨機數填充範圍 (演算法函式物件) |
(C++20) |
給一個範圍的元素賦某個值 (演算法函式物件) |
(C++20) |
給一定數量的元素賦一個值 (演算法函式物件) |
(C++20) |
對一個範圍的元素應用函式 (演算法函式物件) |
將連續函式呼叫的結果賦給一個範圍中的 N 個元素 (函式模板) |