std::fill_n是C++标准库算法头文件<algorithm>中提供的一个函数,作用是向指定起始位置开始的连续n个元素赋值相同的特定值,相比手动写循环赋值,代码更简洁且可读性更高,是处理批量元素初始化的常用工具。

std::fill_n的基本语法
std::fill_n的函数原型如下:
template<class OutputIt, class Size, class T> OutputIt fill_n(OutputIt first, Size count, const T& value);
各个参数的含义如下:
- first:指向填充起始位置的迭代器或者指针,填充操作会从该位置开始向后进行
- count:需要填充的元素个数,必须是非负整数
- value:要填充到元素中的特定值,类型需要和容器元素类型匹配或者可以隐式转换
函数的返回值是填充完成后的下一个位置的迭代器或者指针,如果count为0,返回的就是first本身。
常见使用场景示例
对原生数组填充值
原生数组可以通过数组名(指向首元素的指针)作为first参数,直接调用std::fill_n完成前n个元素的填充:
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int arr[10]; // 定义长度为10的整型数组
// 对数组前5个元素填充值为3
fill_n(arr, 5, 3);
// 打印数组元素验证结果
for (int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
// 输出结果:3 3 3 3 3 0 0 0 0 0
return 0;
}
对vector容器填充值
对于vector这类标准容器,需要使用容器的begin()迭代器作为起始位置,同时要注意容器本身需要有足够的容量,否则会出现未定义行为:
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main() {
// 先初始化vector,预留5个元素的空间并赋默认值0
vector<int> vec(5);
// 对vector前3个元素填充值为10
fill_n(vec.begin(), 3, 10);
for (int num : vec) {
cout << num << " ";
}
// 输出结果:10 10 10 0 0
return 0;
}
对自定义类型容器填充值
只要填充的值类型和容器元素类型匹配,std::fill_n也可以用于自定义类型的容器:
#include <algorithm>
#include <vector>
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int score;
};
int main() {
vector<Student> students(4);
Student default_stu = {"未命名", 0};
// 对前2个学生元素填充默认值
fill_n(students.begin(), 2, default_stu);
for (int i = 0; i < students.size(); i++) {
cout << "第" << i << "个学生:" << students[i].name << " 分数:" << students[i].score << endl;
}
return 0;
}
使用注意事项
避免越界访问
std::fill_n不会检查目标区间是否有足够的空间,如果count的值超过了从first开始到容器末尾的元素数量,就会访问非法内存,导致程序崩溃或者未定义行为。比如下面的代码就是错误的:
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> vec(3); // 只有3个元素
fill_n(vec.begin(), 5, 1); // 错误,要填充5个元素,但是vec只有3个,越界
return 0;
}
和std::fill的区别
std::fill的参数是起始迭代器和结束迭代器,通过区间来指定填充范围,而std::fill_n是通过起始位置和元素个数来指定范围,两者适用场景不同:
| 函数 | 参数形式 | 适用场景 |
|---|---|---|
| std::fill | first, last, value | 已知填充区间的结束位置时使用 |
| std::fill_n | first, count, value | 已知需要填充的元素个数时使用 |
count为0的情况
当count的值为0时,std::fill_n不会执行任何赋值操作,直接返回first,这个特性可以在需要动态判断填充个数的场景中安全使用,不需要额外做count的判断。
总结
std::fill_n是C++中高效处理前n个元素批量赋值的工具,使用时只需要包含<algorithm>头文件,传入正确的起始位置、填充个数和目标值即可。使用时一定要确保填充范围不超过容器的有效容量,避免越界问题,根据场景选择std::fill_n或者std::fill可以让代码更简洁清晰。
std::fill_nC++容器填充算法库数组初始化修改时间:2026-07-20 18:39:29