Initializing Primitive Array to One Value

自作多情 提交于 2019-12-01 17:59:34
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.

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

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.

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

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

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

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.

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