将大小为编译时常量的数组初始化为单个值
Initialize array whose size is a compile-time constant to single value
我有一个 c 风格的数组,其大小由#define
定义,可以根据编译选项进行更改,例如
#if LINUX
# define SIZE 4
#else
# define SIZE 5
#endif
static int myArr[SIZE] = { /* ??? */ };
如何将整个数组初始化为非零值,例如所有42
?
我不知道
C 样式数组的解决方案,尽管使用 constexpr
和 C++17 您可以使用 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
,编译器应该能够对此进行优化。
从 C++20 开始,您可以强制初始化:
static constinit auto myArr = createFilledArray(42);
不确定提案是否已合并:请参阅持续提案
如果你坚持内置数组,你可以在函数中使用静态变量:
template <std::size_t N, std::size_t... Is>
auto arr_helper2(std::index_sequence<Is...>) -> int (&)[N]
{
static int arr[N] = {((void)Is, 42)...};
return arr;
}
template <std::size_t N>
auto arr_helper() -> int (&)[N]
{
return arr_helper2<N>(std::make_index_sequence<N>{});
}
static int (&arr)[SIZE] = arr_helper<SIZE>();
例如:
int main()
{
for (std::size_t i = 0; i < SIZE; ++i)
std::cout << arr[i] << " ";
}
现场演示
对于仍然局限于 C++14 的可怜灵魂,这里有一个 C++14 解决方案,允许您根据函数fill
填充 C 数组:
#include <iostream>
constexpr int SIZE = 5;
constexpr int fill(std::size_t index){ return 42; }
template <int INDEX = 0, int... Values>
struct Helper : Helper<INDEX + 1, Values..., fill(INDEX)> {};
template <int... Values>
struct Helper<SIZE, Values...>{
static constexpr int table[SIZE] = { Values... };
};
template <int... Values>
constexpr int Helper<SIZE, Values...>::table[SIZE];
int main() {
auto constexpr arr = Helper<0>::table;
for(int i = 0; i < SIZE; ++i){
std::cout << arr[i] << 'n';
}
}
但是,请注意,这仅适用于整型类型。
相关文章:
- C++使用整数的压缩数组初始化对象
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 new 和 值进行数组初始化,但没有显式数量的元素
- 运行时C++数组初始化问题
- 使用带有参数包的数组的成员数组初始化类
- 仅通过C++中数组初始化的不同方法,即可在同一输入上获得两个不同的答案
- C++ 2 个指针数组初始化 C2440
- C++结构字符数组初始化
- C++中的多维数组初始化
- constexpr数组初始化
- C++引物动态数组初始化程序的数目超过大小
- 使用std::index_sequence对std::数组初始化进行包扩展
- 当 std 数组初始化太小时,C++会引发错误吗?
- 如何确定结构数组初始化的大小?
- Qt并发错误:数组初始化需要大括号括起来的初始值设定项列表
- 此代码中的数组初始化样式是什么?这是标准的吗?
- C++ 使用数组初始化时的 STL 向量内存管理