Initializing Primitive Array to One Value

前端 未结 6 1326
暗喜
暗喜 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:27

    double A[10] = { value }; // initialize A to value. I do not remember if value has to be compiled constant or not. will not work with automatic arrays

    0 讨论(0)
  • 2021-01-18 04:29

    You can use memset if you want all your values to be zero. Also, if you're only looking to initialize to zero, you can declare your array in such a way that it is placed in the ZI section of memory.

    0 讨论(0)
  • 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 <typename T, size_t N>
    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.

    0 讨论(0)
  • 2021-01-18 04:43

    There are ways of concealing what you are doing with different syntax, and this is what the other answers give you - std::fill, memset, ={} etc. In the general case, though (excluding compiler-specific tricks like the ZI one), think about what needs to be done by the compiled code:

    • it needs to know where your memory block/array starts;
    • it needs to set each element of the block to the value in turn;
    • it needs to check repeatedly whether the end of the block has been reached.

    In other words, there needs to be a loop in a fairly fundamental way.

    0 讨论(0)
  • 2021-01-18 04:44

    Yes, it is possible. The initialization method depends on the context.

    If you are declaring a static or local array, use = {} initializer

    int a[100] = {};  // all zeros
    

    If you are creating an array with new[], use () initializer

    int *a = new int[100](); // all zeros
    

    If you are initializing a non-static member array in the constructor initializer list, use () initializer

    class C {
      int a[100];
    
      C() : a() // all zeros
      {
        ...
      }
    };
    
    0 讨论(0)
  • 2021-01-18 04:46

    If the number is zero you could also use memset (though this is more C-style):

    int a[100];
    memset(a, 0, sizeof(a));
    
    0 讨论(0)
提交回复
热议问题