如何声明 std::array 结构初始化为不同的内联值
How to declare an std::array of structs initialised inline with different values
我正在尝试初始化 std::array
中的结构数组。我知道以下是用整数初始化 std::array
的方法。
std::array<int, 5> arr { {1, 2, 3, 4, 5} };
场景:
但是,假设我有一个这样的结构数组
struct MyStruct {
const char *char_val_1;
const char *char_val_2;
int int_val_1;
double d_val_1;
} my_struct_obj[] = {
{ "a1b1" , "a2b1" , 1 , 1.1 },
{ "a1b2" , "a3b1" , 2 , 1.2 },
{ "a1b3" , "a4b1" , 3 , 1.3 },
{ "a1b4" , "a5b1" , 4 , 1.4 },
{ "a1b5" , "a6b1" , 5 , 1.5 },
{ "a1b6" , "a7b1" , 6 , 1.6 },
{ "a1b7" , "a8b1" , 7 , 1.7 },
{ "a1b8" , "a9b1" , 8 , 1.8 },
{ "a1b9" , "a10b1" , 9 , 1.9 },
};
问题:
我如何创建一个 std::array
的 MyStruct
,每个都使用不同的值集初始化?
就像整数一样,为每个值提供初始值设定项:
std::array<MyStruct, 9> my_struct_arr = {{
{ "a1b1" , "a2b1" , 1 , 1.1 },
{ "a1b2" , "a3b1" , 2 , 1.2 },
{ "a1b3" , "a4b1" , 3 , 1.3 },
{ "a1b4" , "a5b1" , 4 , 1.4 },
{ "a1b5" , "a6b1" , 5 , 1.5 },
{ "a1b6" , "a7b1" , 6 , 1.6 },
{ "a1b7" , "a8b1" , 7 , 1.7 },
{ "a1b8" , "a9b1" , 8 , 1.8 },
{ "a1b9" , "a10b1" , 9 , 1.9 },
}};
我正在尝试初始化 std::array
中的结构数组。我知道以下是用整数初始化 std::array
的方法。
std::array<int, 5> arr { {1, 2, 3, 4, 5} };
场景:
但是,假设我有一个这样的结构数组
struct MyStruct {
const char *char_val_1;
const char *char_val_2;
int int_val_1;
double d_val_1;
} my_struct_obj[] = {
{ "a1b1" , "a2b1" , 1 , 1.1 },
{ "a1b2" , "a3b1" , 2 , 1.2 },
{ "a1b3" , "a4b1" , 3 , 1.3 },
{ "a1b4" , "a5b1" , 4 , 1.4 },
{ "a1b5" , "a6b1" , 5 , 1.5 },
{ "a1b6" , "a7b1" , 6 , 1.6 },
{ "a1b7" , "a8b1" , 7 , 1.7 },
{ "a1b8" , "a9b1" , 8 , 1.8 },
{ "a1b9" , "a10b1" , 9 , 1.9 },
};
问题:
我如何创建一个 std::array
的 MyStruct
,每个都使用不同的值集初始化?
就像整数一样,为每个值提供初始值设定项:
std::array<MyStruct, 9> my_struct_arr = {{
{ "a1b1" , "a2b1" , 1 , 1.1 },
{ "a1b2" , "a3b1" , 2 , 1.2 },
{ "a1b3" , "a4b1" , 3 , 1.3 },
{ "a1b4" , "a5b1" , 4 , 1.4 },
{ "a1b5" , "a6b1" , 5 , 1.5 },
{ "a1b6" , "a7b1" , 6 , 1.6 },
{ "a1b7" , "a8b1" , 7 , 1.7 },
{ "a1b8" , "a9b1" , 8 , 1.8 },
{ "a1b9" , "a10b1" , 9 , 1.9 },
}};