ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

C++ fill()函数最详细介绍

2026/8/8 22:00:39 拓冰建站 浏览量
C++ fill()函数最详细介绍

文章目录

  • 函数参数介绍
  • 函数功能
  • 函数使用注意点
  • 使用例子
    • 1.将数组arr[5]所有元素初始化为0
    • 2.字符数组初始化
    • 3.vector对象


fill函数是C++标准库中的一个算法函数,用于将指定范围内的元素赋值为给定的值。

函数参数介绍

fill( first, last, value );

它接受三个参数:

first:表示要填充的范围的起始迭代器(表示开始位置),指向要填充的第一个元素。
last:表示要填充的范围的结束迭代器(表示结束位置的下一个),指向要填充的最后一个元素的下一个位置。
value:表示要赋给范围内的每个元素的值。

函数功能

fill函数会将范围 [ first, last ) 内的每个元素都设置为 value。
first,last 均表示数组或对象的下标。

函数使用注意点

  1. 只适用于数组和vector对象,不适用于array对象
  2. 需要头文件#include <algorithm>
  3. 编译器环境需要支持C++11的新特性

使用例子

1.将数组arr[5]所有元素初始化为0

fill函数初始化整数数组的每个元素为0
注意:必须知道数组的长度

#include <iostream>
#include <algorithm>using namespace std;int main()
{int arr[5];cout << "原始的arr数组:";for (const auto &element : arr){cout << element << " ";}fill(arr, arr + 5, 0);cout << "\n初始化后,arr数组:";for (const auto &element : arr){cout << element << " ";}cout << endl;return 0;
}

输出:
代码输出

2.字符数组初始化

fill函数将字符串数组的每个元素设置为相同的字符串

#include <iostream>
#include <string>
#include <algorithm>using namespace std;int main()
{string arr[3];cout << "原始的arr数组:";for (const auto &element : arr){cout << element << " ";}fill(arr, arr + 3, "hello");cout << "\n初始化后,arr数组:";for (const auto &element : arr){cout << element << " ";}cout << endl;return 0;
}

输出:
在这里插入图片描述

3.vector对象

fill函数将容器的部分元素设置为特定的值:下标为2到最后的元素设置为0

#include <iostream>
#include <algorithm>
#include <vector>using namespace std;int main()
{vector<int> vec = {1, 2, 3, 4, 5};fill(vec.begin() + 2, vec.end(), 0);for (const auto& element : vec) {cout << element << " ";}cout << endl;return 0;
}

输出:
在这里插入图片描述