Reset C int array to zero : the fastest way?

前端 未结 7 1332
感情败类
感情败类 2020-12-22 18:34

Assuming that we have a T myarray[100] with T = int, unsigned int, long long int or unsigned long long int, what is the fastest way to reset all its content to

7条回答
  •  情歌与酒
    2020-12-22 19:11

    Here's the function I use:

    template
    static void setValue(T arr[], size_t length, const T& val)
    {
        std::fill(arr, arr + length, val);
    }
    
    template
    static void setValue(T (&arr)[N], const T& val)
    {
        std::fill(arr, arr + N, val);
    }
    

    You can call it like this:

    //fixed arrays
    int a[10];
    setValue(a, 0);
    
    //dynamic arrays
    int *d = new int[length];
    setValue(d, length, 0);
    

    Above is more C++11 way than using memset. Also you get compile time error if you use dynamic array with specifying the size.

提交回复
热议问题