c++关于数组初始化的那点事

本文详细比较了C++中用于数组初始化的两种方法:memset函数与fill函数。介绍了它们的使用场景、语法及适用类型,强调了memset适用于char型数组的全0或全1初始化,而fill函数则能更灵活地为各种类型数组赋值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

借鉴https://blog.youkuaiyun.com/liuchuo/article/details/52296646

感恩(^_^*)

在做题过程中肯定遇到过数组全赋值为某个值的,这时候是不是想到memset 辽,但是发现好像不行耶 :) 

memset函数

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


fill函数

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

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

fill(arr, arr + n, 要填入的内容);
例如:

#include <cstdio>
#include <algorithm>
using namespace std;
int main() {
    int arr[10];
    fill(arr, arr + 10, 2);
    return 0;
}
#include <algorithm>
#include <vector>
#include <iostream>
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;
}    

 memset是以字节填充只能填充0,-1和inf  

#include <iostream>
#include <cstring>
using namespace std;
int main(){
    int a[20];
    memset(a, 0, sizeof a);
    return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
int main(){
    int a[20];
    memset(a,0x3f3f3f,sizeof(a));
    return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
int main(){
    int a[20];
    memset(a,1,sizeof(a));
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值