• 【C++】fill函数,fill与memset函数的区别


    转载自:https://blog.csdn.net/liuchuo/article/details/52296646

    memset函数

    按照字节填充某字符
    在头文件<cstring>里面
    fill函数

    按照单元赋值,将一个区间的元素都赋同一个值
    在头文件<algorithm>里面
    因为memset函数按照字节填充,所以一般memset只能用来填充char型数组,(因为只有char型占一个字节)如果填充int型数组,除了0和-1,其他的不能。因为只有00000000 = 0,-1同理,如果我们把每一位都填充“1”,会导致变成填充入“11111111”

    而fill函数可以赋值任何,而且使用方法特别简便:

    例如int数组:fill(arr, arr + n, 要填入的内容);
    #include <cstdio>
    #include <algorithm>
    using namespace std;
    int main() {
    int arr[10];
    fill(arr, arr + 10, 2);
    return 0;
    }
    1
    2
    3
    4
    5
    6
    7
    8
    vector也可以:fill(v.begin(), v.end(), 要填入的内容);
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    int main() {
    vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    fill(v.begin(), v.end(), -1);
    return 0;
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    而memset的使用方法是:
    #include <iostream>
    #include <cstring>
    using namespace std;
    int main(){
    int a[20];
    memset(a, 0, sizeof a);
    return 0;
    }
    ---------------------
    作者:柳婼
    来源:CSDN
    原文:https://blog.csdn.net/liuchuo/article/details/52296646
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    [写代码]处理一组lrc歌词文件
    [ubuntu]windows重装以后,恢复grub引导
    [HDOJ1878]欧拉回路
    [写代码]解析自定义数据库文件的思路
    [写代码]wordList——百词斩CLI版
    [HDOJ2544]最短路
    [HDOJ1285] 确定比赛名次
    [HDOJ1232]畅通工程
    [HDOJ2717]Catch That Cow
    jQuery实现点击开关图片切换
  • 原文地址:https://www.cnblogs.com/joelwang/p/10586796.html
Copyright © 2020-2023  润新知