std::ranges::fill_n
来自 cppreference.cn
定义于头文件 <algorithm> |
||
调用签名 (Call signature) |
||
template< class T, std::output_iterator<const T&> O > constexpr O fill_n( O first, std::iter_difference_t<O> n, const T& value ); |
(C++20 起) (直到 C++26) |
|
template< class O, class T = std::iter_value_t<O> > requires std::output_iterator<O, const T&> |
(C++26 起) | |
将给定的 value 赋值给范围 [
first,
first + n)
中的所有元素。
本页描述的类函数实体是 算法函数对象(非正式地称为 niebloids),即
目录 |
[编辑] 参数
first | - | 要修改的元素范围的起始迭代器 |
n | - | 要修改的元素数量 |
value | - | 要赋值的值 |
[编辑] 返回值
一个输出迭代器,与 first + n 比较相等。
[编辑] 复杂度
恰好 n 次赋值。
[编辑] 可能的实现
struct fill_n_fn { template<class O, class T = std::iter_value_t<O>> requires std::output_iterator<O, const T&> constexpr O operator()(O first, std::iter_difference_t<O> n, const T& value) const { for (std::iter_difference_t<O> i {}; i != n; ++first, ++i) *first = value; return first; } }; inline constexpr fill_n_fn fill_n {}; |
[编辑] 注意
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_lib_algorithm_default_value_type |
202403 |
(C++26) | 算法的列表初始化 |
[编辑] 示例
运行此代码
#include <algorithm> #include <complex> #include <iostream> #include <string> #include <vector> void println(const auto& v) { for (const auto& elem : v) std::cout << ' ' << elem; std::cout << '\n'; } int main() { constexpr auto n{8}; std::vector<std::string> v(n, "▓▓░░"); println(v); std::ranges::fill_n(v.begin(), n, "░░▓▓"); println(v); std::vector<std::complex<double>> nums{{1, 3}, {2, 2}, {4, 8}}; println(nums); #ifdef __cpp_lib_algorithm_default_value_type std::ranges::fill_n(nums.begin(), 2, {4, 2}); #else std::ranges::fill_n(nums.begin(), 2, std::complex<double>{4, 2}); #endif println(nums); }
输出
▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ (1,3) (2,2) (4,8) (4,2) (4,2) (4,8)
[编辑] 参阅
(C++20) |
给一个范围的元素赋某个值 (算法函数对象) |
(C++20) |
将一定数量的元素复制到一个新位置 (算法函数对象) |
(C++20) |
将一个函数的结果保存在一个范围中 (算法函数对象) |
(C++20) |
对一个范围的元素应用函数 (算法函数对象) |
(C++26) |
用来自均匀随机位生成器的随机数填充范围 (算法函数对象) |
将给定值复制赋给一个范围中的 N 个元素 (函数模板) |