std:: fill_n
|
定义于头文件
<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 起) | |
|
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}; // 将前5个元素的值替换为-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)
|
为指定数量的元素赋值
(算法函数对象) |