Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an array of struct in C++?

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.

like image 577
Alexander Galkin Avatar asked Dec 16 '11 13:12

Alexander Galkin


People also ask

How do you initialize an array of structs?

If you have multiple fields in your struct (for example, an int age ), you can initialize all of them at once using the following: my_data data[] = { [3]. name = "Mike", [2]. age = 40, [1].

How do you create an array of structs in Objective C?

@interface Foo : NSObject { NSString *name; NSArray *books; } @end A->name = @"Clancy, Thomas"; A->books = [[NSArray alloc] initWithObjects:@"Book 1" @"Book2",nil]; self. authors = [[NSArray alloc] initWithObjects:A, nil];

How are structs initialized in C?

Structure members can be initialized using curly braces '{}'.


1 Answers

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.

like image 92
Björn Pollex Avatar answered Sep 21 '22 02:09

Björn Pollex