如何在 C++ 中初始化结构数组? [英] How to initialize an array of struct in C++?
问题描述
我的 C++ 代码中有以下 struct
(我使用的是 Visual Studio 2010):
I have the following struct
in my C++ code (I am using Visual Studio 2010):
struct mydata
{
string scientist;
double value;
};
我想做的是能够以快速的方式初始化它们,类似于 C99 中的数组初始化或 C# 中的类初始化,一些á la:
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:
mydata data[] = { { scientist = "Archimedes", value = 2.12 },
{ scientist = "Vitruvius", value = 4.49 } } ;
如果这在 C++ 中无法用于结构数组,我可以为对象数组执行此操作吗?换句话说,数组的底层数据类型并不那么重要,重要的是我有一个数组,而不是一个列表,并且我可以这样编写初始化器.
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++ 中的语法几乎完全相同(只是省略了命名参数):
The syntax in C++ is almost exactly the same (just leave out the named parameters):
mydata data[] = { { "Archimedes", 2.12 },
{ "Vitruvius", 4.49 } } ;
在 C++03 中,只要数组类型是 聚合.在 C++11 中,这适用于任何具有适当构造函数的对象.
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++ 中初始化结构数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!