c++ - 在没有循环的情况下用非零值初始化 C 风格的数组

标签 c++ arrays

我们知道 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 )

有没有什么方法可以在不使用 vectoralgorhtm 的情况下用非零值初始化整个数组?

也许 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/

相关文章:

c++ - 当 enum 有重复值时,如果将 int 值转换为 enum 会发生什么?

javascript - 将对象映射到数组然后使用 jQuery 输出值

java - 定位二维数组中元素的坐标

python - for 循环 : C++ and python

c++ - 在 C++17 中实现 iterator 和 const_iterator 的正确方法是什么?

Python:结构的所有元素都会随着一个人的变化而变化

python - 用python打乱一个数组,用python随机化数组项顺序

arrays - 用于创建 JSON 文件的 Bash 脚本

c++ - 时钟()返回0

c++ - 控件到达非空函数警告 C++ 的末尾