黄山做网站,上广东建设厅网站,国家企业信用公示信息年报全国,php 7 wordpress文章目录 函数参数介绍函数功能函数使用注意点使用例子1.将数组arr[5]所有元素初始化为02.字符数组初始化3.vector对象 fill函数是C标准库中的一个算法函数#xff0c;用于将指定范围内的元素赋值为给定的值。 函数参数介绍
fill( first, last, value );它接受三个参数#… 文章目录 函数参数介绍函数功能函数使用注意点使用例子1.将数组arr[5]所有元素初始化为02.字符数组初始化3.vector对象 fill函数是C标准库中的一个算法函数用于将指定范围内的元素赋值为给定的值。 函数参数介绍
fill( first, last, value );它接受三个参数
first表示要填充的范围的起始迭代器表示开始位置指向要填充的第一个元素。 last表示要填充的范围的结束迭代器表示结束位置的下一个指向要填充的最后一个元素的下一个位置。 value表示要赋给范围内的每个元素的值。
函数功能
fill函数会将范围 [ first, last ) 内的每个元素都设置为 value。 first,last 均表示数组或对象的下标。
函数使用注意点
只适用于数组和vector对象不适用于array对象需要头文件#include algorithm编译器环境需要支持C11的新特性
使用例子
1.将数组arr[5]所有元素初始化为0
fill函数初始化整数数组的每个元素为0 注意必须知道数组的长度
#include iostream
#include algorithmusing 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 algorithmusing 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 vectorusing namespace std;int main()
{vectorint vec {1, 2, 3, 4, 5};fill(vec.begin() 2, vec.end(), 0);for (const auto element : vec) {cout element ;}cout endl;return 0;
}输出