我们知道 C++ 允许 initialization of C-style arrays with zeros :
int a[5] = {0};
// or
int a[5] = {};
同样适用于 std::array
std::array a<int, 5> = {};
但是,这是行不通的:
int a[5] = {33}; // in memory( 33, 0, 0, 0, 0 )
std::array<int, 5> = {33}; // in memory( 33, 0, 0, 0, 0 )
有没有什么方法可以在不使用 vector
或 algorhtm
的情况下用非零值初始化整个数组?
也许 constexpr
能帮上忙?什么是最佳解决方案?
附言:
GCC 提供 this syntax
int a[5] = {[0 ... 4] = 33};
但我不确定它是否对其他编译器有效。
最佳答案
你有什么反对 <algorithm>
?我认为这很干净:
int a[5]; // not initialized here yet
std::fill(std::begin(a), std::end(a), 33); // everything initialized to 33
关于c++ - 在没有循环的情况下用非零值初始化 C 风格的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36810796/