简体   繁体   English

在结构初始化中传递数组

[英]Passing an array in struct initialization

I would like to create a struct which contains both an int and an array of int.我想创建一个包含 int 和 int 数组的结构。 So I define it like所以我把它定义为

struct my_struct {
int N ;
int arr[30] ;
int arr[30][30] ;
}

Then I would like to initialize it with an array which I have already defined and initialized, for example然后我想用一个我已经定义和初始化的数组来初始化它,例如

int my_arr[30] ;
for (int i = 0; i < 30; ++i)
{
my_arr[i] = i ;
}

Then I thought I could initialize a struct as然后我想我可以将一个结构初始化为

my_struct A = {30,my_arr}

but it doesn't seem to work (gives conversion error).但它似乎不起作用(给出转换错误)。 Ps and how would it work with a 2d array? Ps 以及它如何与二维数组一起使用?

Arrays cannot be copy-initialised. Arrays 不能被复制初始化。 This isn't particular to the array being member of a class;这并不是特定于作为 class 成员的数组; same can be reproduced like this:同样可以这样重现:

int a[30] = {};
int b[30] = a; // ill-formed

You can initialise array elements like this:您可以像这样初始化数组元素:

my_struct A = {30, {my_arr[0], my_arr[1], my_arr[2], //...

But that's not always very convenient.但这并不总是很方便。 Alternatively, you can assign the array values using a loop like you did initially.或者,您可以像最初那样使用循环分配数组值。 You don't have to write the loop either, there's a standard algorithm for this called std::copy .您也不必编写循环,有一个称为std::copy的标准算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM