std::fill
来自 cppreference.cn
定义于头文件 <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) |
给一个范围的元素赋某个值 (算法函数对象) |