1、memset函数给数组按字节赋值 为内存做初始化工作
需要头文件#include <cstring>
(1)给char类型数组按字节赋值,其中char占一个字节
(2)int类型数组按字节赋值0和1,其中int占4个字节=4*8位
eg1: memset(a,0,sizeof(a)); // 将a数组所有元素均赋值为0
eg2: memset(b,1,sizeof(b));// 将 b 数组所有元素均赋值为二进制数 2^0+2^8+2^16+2^24=16843009
eg3: memset(c,0,5);将c数组前5个字节都赋值为0,所以只能确定c[0]等于0,其他元素值不确定
2、fill函数 给数组按元素赋值
需要头文件#include <algorithm>
(1)可以是整个数组,也可以是部分连续元素,可以赋任何值
(2)eg:fill (array+3,array+6,8); // fill(开始first,结束last,赋的值value)
fill
会改变first
和last
之间的所有元素,包括first
但不包括last
3、体会memset函数
#include<iostream>
#include<cstring>
using namespace std;
int main(){
int a[10],b[10],c[10],d[10],i;
memset(a,0,sizeof(a)); // 将a数组所有元素均赋值为0
for(i = 0; i < 9; i++) cout << a[i] << " " ;
cout << a[9] << endl;
memset(b,1,sizeof(b));// 将 b 数组所有元素均赋值为
//二进制数 2^0+2^8+2^16+2^24=16843009
for(i = 0; i < 9; i++) cout << b[i] << " " ;
cout << b[9] << endl;
memset(c,0,5);
//将 c 数组前 5 个字节都赋值为 0,所以只能确定 c[0]
//等于0,其他元素值不确定
for(i = 0; i < 9; i++) cout << c[i] << " " ;
cout << c[9] << endl;
fill(d,d+5,8);
//将 d 数组前 5 个元素都赋值为 8,其他元素值不确定
for(i = 0; i < 9; i++) cout << d[i] << " " ;
cout << d[9] << endl;
return 0;
}