std::generate
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
template< class ForwardIt, class Generator > void generate( ForwardIt first, ForwardIt last, Generator g ); |
(1) | (C++20 起為 constexpr) |
template< class ExecutionPolicy, class ForwardIt, class Generator > void generate( ExecutionPolicy&& policy, |
(2) | (C++17 起) |
1) 將範圍
[
first,
last)
內的每個元素賦值為給定函式物件 g 生成的值。2) 同 (1),但根據 policy 執行。
僅當滿足以下所有條件時,此過載才參與過載決議
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 為 true。 |
(C++20 前) |
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> 為 true。 |
(C++20 起) |
目錄 |
[編輯] 引數
first, last | - | 定義要生成元素的範圍的迭代器對 | ||||||
policy | - | 要使用的 執行策略 | ||||||
g | - | 將被呼叫的生成器函式物件。 函式的簽名應等效於以下內容
型別 Ret 必須是使得 ForwardIt 型別的物件可以被解引用並賦值為 Ret 型別的值。 | ||||||
型別要求 | ||||||||
-ForwardIt 必須滿足 LegacyForwardIterator 的要求。 |
[編輯] 複雜度
恰好 std::distance(first, last) 次 g() 呼叫和賦值。
[編輯] 異常
帶有名為 ExecutionPolicy
的模板引數的過載會按如下方式報告錯誤:
- 若作為演算法一部分呼叫的函式執行時丟擲異常且 `ExecutionPolicy` 是標準策略之一,則呼叫 std::terminate。對於任何其他 `ExecutionPolicy`,行為是實現定義的。
- 如果演算法未能分配記憶體,則丟擲 std::bad_alloc。
[編輯] 可能的實現
template<class ForwardIt, class Generator> constexpr //< since C++20 void generate(ForwardIt first, ForwardIt last, Generator g) { for (; first != last; ++first) *first = g(); } |
[編輯] 示例
執行此程式碼
#include <algorithm> #include <iostream> #include <vector> void println(std::string_view fmt, const auto& v) { for (std::cout << fmt; const auto& e : v) std::cout << e << ' '; std::cout << '\n'; }; int f() { static int i; return ++i; } int main() { std::vector<int> v(5); std::generate(v.begin(), v.end(), f); println("v: ", v); // Initialize with default values 0,1,2,3,4 from a lambda function // Equivalent to std::iota(v.begin(), v.end(), 0); std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; }); println("v: ", v); }
輸出
v: 1 2 3 4 5 v: 0 1 2 3 4
[編輯] 參閱
將給定值複製賦給一個範圍中的每個元素 (函式模板) | |
將連續函式呼叫的結果賦給一個範圍中的 N 個元素 (函式模板) | |
(C++11) |
以起始值的連續增量填充一個範圍 (函式模板) |
(C++20) |
將一個函式的結果儲存在一個範圍中 (演算法函式物件) |