How to initialize an array of struct in C++?
The syntax in C++ is almost exactly the same (just leave out the named parameters):
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.
Alexander Galkin
From December, 2013 I work as Software Developer at Microsoft Bing. Till August 2017 I was working from the office in Sunnyvale, California and then relocated back to Hamburg, Germany, where I continue to work for the Bing Metrics Team. Until October 2013 I worked as a Senior Developer at Eurofins in Hamburg, Germany. Microsoft Azure Insider Microsoft Expert Student Partner in German MSP Team. 7x MTA | 17x MCTS | 5x MCITP | 5x MCPD | Azure MCSA | MCT Microsoft MCP Transcript (ID: 827426, password: microsoft) Careers 2.0 at SO Blog "Managed meets functional" Twitter Facebook Google+ profile Email: [email protected] @alaudo
Updated on July 09, 2022Comments
-
Alexander Galkin almost 2 years
I have the following
struct
in my C++ code (I am using 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:
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.