将大小为编译时常量的数组初始化为单个值 [英] Initialize array whose size is a compile-time constant to single value
问题描述
我有一个c样式的数组,其大小由 #define
定义,并且可以根据编译选项进行更改,例如
I have a c-style array whose size is defined by a #define
and can change based on compiling options, e.g.
#if LINUX
# define SIZE 4
#else
# define SIZE 5
#endif
static int myArr[SIZE] = { /* ??? */ };
如何将整个数组初始化为非零值,例如所有 42
?
How can I initialize the whole array to a non-zero value, for example all 42
?
推荐答案
我不知道C样式数组的解决方案使用 constexpr
和C ++ 17,可以使用 std :: array
做到这一点。
I don't know a solution for C-style arrays, though with constexpr
and C++17 you could do this with std::array
.
constexpr std::array<int, SIZE> createFilledArray (int value){
std::array<int, SIZE> a{0};
for (auto i = 0; i < SIZE; ++i)
a[i] = value;
return a;
}
static constexpr auto myArr = createFilledArray(42);
这样做的缺点是您无法更改数组。
如果从变量中删除 constexpr
,则编译器应该能够对此进行优化。
The disadvantage of this is that you can't change the array.
If you remove the constexpr
from the variable, your compiler should be able to optimize this.
从C ++ 20开始,您可以强制初始化:
From C++20 on, you can force the initialization:
static constinit auto myArr = createFilledArray(42);
不确定该提案是否已合并:请参见 constinit提案
Not sure if the proposal is already merged in: see constinit proposal
这篇关于将大小为编译时常量的数组初始化为单个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!