[C++] memset函数和fill函数

tech2025-06-12  6

1. memset 函数

(1)头文件 : cstring (2)memset(数组名,值,sizeof(数组名)), 值 取一个字节(后8位) (3)按字节填充 类型取值char都可取(char类型只有一个字节)booltrue,false(同上)int0 ,-1 #include<iostream> #include<cstring> using namespace std; int a[5] = {1, 2, 3, 4, 5}; void print() { for(int i = 0; i < 5; i++) cout << a[i] << " "; cout << endl; } int main() { cout << "原数组:" << endl; print(); cout << "赋值为0或-1数组:" << endl; memset(a, -1, sizeof(a)); //memset(a, 0, sizeof(a)); print(); cout << "赋值为1数组:" << endl; memset(a, 1, sizeof(a)); print(); return 0; } 原数组: 1 2 3 4 5 赋值为0-1数组: -1 -1 -1 -1 -1 赋值为1数组: 16843009 16843009 16843009 16843009 16843009

注意: 当赋值为1时, 1的一个字节为 0000 0001, 赋值给int类型(int类型为4个字节)的数组,即为:0000 0001 0000 0001 0000 0001 0000 0001,转化为10进制为 16843009。

2. fill 函数

(1)头文件 : algorithm (2)fill(数组名,数组名 + n,值) ,值为任意值 (3)按单元填充,可以填充一个区间内所有的值 #include<iostream> #include<algorithm> using namespace std; int a[5] = {1, 2, 3, 4, 5}; void print() { for(int i = 0; i < 5; i++) cout << a[i] << " "; cout << endl; } int main() { cout << "原数组:" << endl; print(); cout << "赋值为任意值的数组:" << endl; fill(a, a + 5, 100); print(); fill(a, a + 5, -1); print(); return 0; } 原数组: 1 2 3 4 5 赋值为任意值的数组: 100 100 100 100 100 -1 -1 -1 -1 -1
最新回复(0)