std::fill_n
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
(1) | ||
template< class OutputIt, class Size, class T > OutputIt fill_n( OutputIt first, Size count, const T& value ); |
(C++20 起為 constexpr) (直到 C++26) |
|
template< class OutputIt, class Size, class T = typename std::iterator_traits |
(C++26 起) | |
(2) | ||
template< class ExecutionPolicy, class ForwardIt, class Size, class T > |
(C++17 起) (直到 C++26) |
|
template< class ExecutionPolicy, class ForwardIt, class Size, |
(C++26 起) | |
1) 如果 count > 0,則將給定 value 賦值給起始於 first 的範圍內的前 count 個元素。否則不執行任何操作。
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 | - | 要修改的元素範圍的起始迭代器 |
count | - | 要修改的元素數量 |
value | - | 要賦值的值 |
policy | - | 要使用的 執行策略 |
型別要求 | ||
-OutputIt 必須滿足 LegacyOutputIterator 的要求。 | ||
-ForwardIt 必須滿足 LegacyForwardIterator 的要求。 |
[編輯] 返回值
如果 count > 0,則返回指向最後一個被賦值元素之後的迭代器,否則返回 first。
[編輯] 複雜度
恰好 std::max(0, count) 次賦值。
[編輯] 異常
帶有名為 ExecutionPolicy
的模板引數的過載會按如下方式報告錯誤:
- 如果作為演算法一部分呼叫的函式丟擲異常,並且
ExecutionPolicy
是標準策略之一,則呼叫 std::terminate。對於任何其他ExecutionPolicy
,行為是實現定義的。 - 如果演算法未能分配記憶體,則丟擲 std::bad_alloc。
[編輯] 可能的實現
fill_n |
---|
template<class OutputIt, class Size, class T = typename std::iterator_traits<OutputIt>::value_type> OutputIt fill_n(OutputIt first, Size count, const T& value) { for (Size i = 0; i < count; i++) *first++ = value; return first; } |
[編輯] 注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_algorithm_default_value_type |
202403 |
(C++26) | 演算法的列表初始化 (1,2) |
[編輯] 示例
執行此程式碼
#include <algorithm> #include <complex> #include <iostream> #include <iterator> #include <vector> int main() { std::vector<int> v1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // replace values of the first 5 elements with -1 std::fill_n(v1.begin(), 5, -1); std::copy_n(v1.cbegin(), v1.size(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; std::vector<std::complex<double>> nums{{1, 3}, {2, 2}, {4, 8}}; #ifdef __cpp_lib_algorithm_default_value_type std::fill_n(nums.begin(), 2, {4, 2}); #else std::fill_n(nums.begin(), 2, std::complex<double>{4, 2}); #endif std::copy_n(nums.cbegin(), nums.size(), std::ostream_iterator<std::complex<double>>(std::cout, " ")); std::cout << '\n'; }
輸出
-1 -1 -1 -1 -1 5 6 7 8 9 (4,2) (4,2) (4,8)
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 283 | C++98 | 要求 T 為 可複製賦值 (CopyAssignable),但T 不總是可寫入 OutputIt |
改為要求可寫入 |
LWG 426 | C++98 | 複雜度要求是“恰好 count 次賦值”,如果 count 為負數,則此要求錯誤。 |
如果沒有賦值 count 為非正數 |
LWG 865 | C++98 | 未返回填充範圍後第一個元素的位置 未返回填充範圍 |
已返回 |
[編輯] 參閱
將給定值複製賦給一個範圍中的每個元素 (函式模板) | |
(C++20) |
給一定數量的元素賦一個值 (演算法函式物件) |