fill和memset函数(C++)

memset函数

头文件 #include<string.h>

因为memset函数按照字节填充,所以一般memset只能用来填充char型数组,(因为只有char型占一个字节)如果填充int型数组,除了0和-1,其他的不能。因为只有00000000 = 0,-1同理,如果我们把每一位都填充“1”,会导致变成填充入“11111111”。

理论上只能初始化为0和-1,而且必须为数组,但是memset()函数还能将int型数组初始化为INF(0x3f3f3f3f)——最大值1061109567

具体介绍https://blog.csdn.net/weixin_44635198/article/details/114084023

代码案例

#include<iostream>
#include<string.h>

using namespace std;

int a[5];
int b[5];
int c[5];
int d[5];

void print(int v[]) {
    
    
	for(int i=0; i<5; i++) {
    
    
		cout << v[i] << " ";
	}
	cout << endl;
}

int main(){
    
    
	
	memset(a,0,sizeof(a));
	memset(b,-1,sizeof(a));
	memset(c,1,sizeof(a));
	memset(d,0x3f,sizeof(d));
	print(a);
	print(b);
	print(c);
	print(d);
	return 0;
}


在这里插入图片描述

full函数

头文件 #include

代码案例

#include<iostream>
#include<vector>

using namespace std;

int main(int argc, char** argv) {
    
    
	int arr[6];
	vector<int> v(10);
	int f[6][5];
	
	fill(arr, arr + 6, 3);   //普通数组
	fill(v.begin(), v.end(), 2);//vector
	fill(f[0], f[0]+5*6, 6);    //二维数组
	
	for(int i=0; i<6; i++) {
    
    
		cout << arr[i] << " ";
	}
	cout << endl;
	for(int i=0; i<v.size(); i++) {
    
    
		cout << v[i] << " ";
	}
	cout << endl;
	for(int i=0; i<6; i++) {
    
    
		for(int j=0; j<6; j++) {
    
    
			cout << f[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}


在这里插入图片描述

二者区别点

  • memset主要对数组进行赋值,且对int型数组,只能赋值为0和-1
  • fill函数可以对数组或其他容器,进行赋值,值可以任意
  • fill和memset都作用于int型数组上时,fill方法速度较慢

猜你喜欢

转载自blog.csdn.net/weixin_44635198/article/details/114086976
今日推荐