std::fill
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
(1) | ||
template< class ForwardIt, class T > void fill( ForwardIt first, ForwardIt last, const T& value ); |
(C++20 起為 constexpr) (直到 C++26) |
|
template< class ForwardIt, class T = typename std::iterator_traits <ForwardIt>::value_type > |
(C++26 起) | |
(2) | ||
template< class ExecutionPolicy, class ForwardIt, class T > void fill( ExecutionPolicy&& policy, |
(C++17 起) (直到 C++26) |
|
template< class ExecutionPolicy, class ForwardIt, class T = typename std::iterator_traits |
(C++26 起) | |
1) 將給定 value 賦值給範圍
[
first,
last)
中的所有元素。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 起) |
如果 value 不能 寫入 first,則程式格式錯誤。
目錄 |
[編輯] 引數
first, last | - | 定義要修改的元素範圍的迭代器對 |
value | - | 要賦值的值 |
policy | - | 要使用的 執行策略 |
型別要求 | ||
-ForwardIt 必須滿足 LegacyForwardIterator 的要求。 |
[編輯] 複雜度
精確地 std::distance(first, last) 次賦值。
[編輯] 異常
帶有名為 ExecutionPolicy
的模板引數的過載會按如下方式報告錯誤:
- 如果作為演算法一部分呼叫的函式丟擲異常,並且
ExecutionPolicy
是標準策略之一,則呼叫 std::terminate。對於任何其他ExecutionPolicy
,行為是實現定義的。 - 如果演算法未能分配記憶體,則丟擲 std::bad_alloc。
[編輯] 可能的實現
fill (1) |
---|
template<class ForwardIt, class T = typename std::iterator_traits<ForwardIt>::value_type> void fill(ForwardIt first, ForwardIt last, const T& value) { for (; first != last; ++first) *first = value; } |
[編輯] 注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_algorithm_default_value_type |
202403 |
(C++26) | 演算法的列表初始化 (1,2) |
[編輯] 示例
執行此程式碼
#include <algorithm> #include <complex> #include <iostream> #include <vector> void println(const auto& seq) { for (const auto& e : seq) std::cout << e << ' '; std::cout << '\n'; } int main() { std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8}; println(v); // set all of the elements to 8 std::fill(v.begin(), v.end(), 8); println(v); std::vector<std::complex<double>> nums{{1, 3}, {2, 2}, {4, 8}}; println(nums); #ifdef __cpp_lib_algorithm_default_value_type std::fill(nums.begin(), nums.end(), {4, 2}); #else std::fill(nums.begin(), nums.end(), std::complex<double>{4, 2}); #endif println(nums); }
輸出
0 1 2 3 4 5 6 7 8 8 8 8 8 8 8 8 8 8 (1,3) (2,2) (4,8) (4,2) (4,2) (4,2)
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 283 | C++98 | 要求 T 為 可複製賦值 (CopyAssignable),但T 不總是可寫入 ForwardIt |
改為要求可寫入 |
[編輯] 參閱
將給定值複製賦給一個範圍中的 N 個元素 (函式模板) | |
(C++11) |
將一個範圍的元素複製到一個新位置 (函式模板) |
將連續函式呼叫的結果賦給一個範圍中的每個元素 (函式模板) | |
對一個範圍的元素應用函式,並將結果儲存在目標範圍中 (函式模板) | |
(C++20) |
給一個範圍的元素賦某個值 (演算法函式物件) |