如何在c++中初始化结构数组?

时间:2022-02-04 16:54:06

I have the following struct in my C++ code (I am using Visual Studio 2010):

我的c++代码中有以下结构(我使用的是Visual Studio 2010):

struct mydata
{
    string scientist;
    double value;
};

What I would like to do is to be able to initialize them in a quick way, similar to array initialization in C99 or class initialization in C#, something á la:

我想做的是能够快速地初始化它们,类似于C99中的数组初始化或者c#中的类初始化,有点像:

mydata data[] = { { scientist = "Archimedes", value = 2.12 }, 
                  { scientist = "Vitruvius", value = 4.49 } } ;

If this is not possible in C++ for an array of structs, can I do it for an array of objects? In other words, the underlying data type for an array isn't that important, it is important that I have an array, not a list, and that I can write initializers this way.

如果在c++中,对于一个结构体数组,这是不可能的,那么对于一个对象数组,我可以这样做吗?换句话说,数组的底层数据类型并不重要,重要的是我有一个数组,而不是一个列表,我可以用这种方式编写初始化器。

1 个解决方案

#1


47  

The syntax in C++ is almost exactly the same (just leave out the named parameters):

c++中的语法几乎完全相同(只要去掉命名的参数):

mydata data[] = { { "Archimedes", 2.12 }, 
                  { "Vitruvius", 4.49 } } ;

In C++03 this works whenever the array-type is an aggregate. In C++11 this works with any object that has an appropriate constructor.

在c++ 03中,每当arraytype是一个聚合体时,它就会起作用。在c++ 11中,这适用于任何具有适当构造函数的对象。

#1


47  

The syntax in C++ is almost exactly the same (just leave out the named parameters):

c++中的语法几乎完全相同(只要去掉命名的参数):

mydata data[] = { { "Archimedes", 2.12 }, 
                  { "Vitruvius", 4.49 } } ;

In C++03 this works whenever the array-type is an aggregate. In C++11 this works with any object that has an appropriate constructor.

在c++ 03中,每当arraytype是一个聚合体时,它就会起作用。在c++ 11中,这适用于任何具有适当构造函数的对象。