fill函数与memset函数的区别(c++)

    科技2022-07-16  125

    fill函数: 将一个区间的元素都赋予某个值。 头文件:<algorithm> 函数参数:fill(begin, end, value); value为要填入的值

    fill使用:

    #include<iostream> #include <algorithm> using namespace std; int main() { int num[5]; fill(num, num + 5, 3); return 0; }

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

    memset使用:

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

    另外,memset比fill快,如果填入0、-1、INF最好使用memset。

    Processed: 0.010, SQL: 8