Initializing Primitive Array to One Value

前端 未结 6 1363
暗喜
暗喜 2021-01-18 03:55

Is there a way to initialize an array of primitives, say a integer array, to 0? Without using a for loop? Looking for concise code that doesn\'t involve a for loop.

6条回答
  •  春和景丽
    2021-01-18 04:32

    int array[10] = {}; // to 0
    
    std::fill(array, array + 10, x); // to x
    

    Note if you want a more generic way to get the end:

    template 
    T* endof(T (&pArray)[N])
    {
        return &pArray[0] + N;
    }
    

    To get:

    std::fill(array, endof(array), x); // to x (no explicit size)
    

    It should be mentioned std::fill is just a wrapper around the loop you're trying to avoid, and = {}; might be implemented in such terms.

提交回复
热议问题