std::fill_n
翻译:https://en.cppreference.com/w/cpp/algorithm/fill_n
定义在头文件<algorithm>
函数声明:
1 2 3 4 5 6 7 8 9 | template < class OutputIt, class Size, class T > void fill_n( OutputIt first, Size count, const T& value ); // (until C++11) template < class OutputIt, class Size, class T > OutputIt fill_n( OutputIt first, Size count, const T& value ); //(since C++11) (until C++20) template < class OutputIt, class Size, class T > constexpr OutputIt fill_n( OutputIt first, Size count, const T& value ); // (since C++20) template < class ExecutionPolicy, class ForwardIt, class Size, class T > ForwardIt fill_n( ExecutionPolicy&& policy, ForwardIt first, Size count, const T& value ); (2) //(since C++17) |
函数解释:
1)如果参数 count > 0, 那么在参数 first 的开始位置,分配 count 个 value 元素。否则什么也不做
2)同1,按照策略执行。但是重载方案不会参与,除非
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
或者
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>
是真。
函数参数:
first:要被修改元素的起始翻译的开始地址
count:修改元素的数量
value:被分配的元素的值
policy:使用的执行策略。
类型要求:
OutputIt 和 ForwardIt 必须要满足对应的要求
返回值:
无
函数实现:
template<class OutputIt, class Size, class T> OutputIt fill_n(OutputIt first, Size count, const T& value) { for (Size i = 0; i < count; i++) { *first++ = value; } return first; }
例子:
#include <algorithm> #include <vector> #include <iostream> #include <iterator> int main() { std::vector<int> v1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::fill_n(v1.begin(), 5, -1); std::copy(begin(v1), end(v1), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; }
输出结果:
-1 -1 -1 -1 -1 5 6 7 8 9
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2019-06-06 make文件基础用法