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


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;
}

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

  • 12
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值