Initializing Primitive Array to One Value

半城伤御伤魂 提交于 2019-12-01 16:25:22

问题


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.

:)


回答1:


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.




回答2:


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
  {
    ...
  }
};



回答3:


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.




回答4:


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

int a[100];
memset(a, 0, sizeof(a));



回答5:


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




回答6:


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.



来源:https://stackoverflow.com/questions/2625551/initializing-primitive-array-to-one-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!