46

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.

Alexander Galkin
  • 12,086
  • 12
  • 63
  • 115
  • 1
    There is no reason why it shouldn't work... (btw that would be `.scientist = ...`) Have you tried? – fge Dec 16 '11 at 13:03
  • @fge Yes, it's called aggregate initialisation and is further explained in detail [here](http://en.cppreference.com/w/cpp/language/aggregate_initialization) – pfabri Dec 10 '17 at 11:12

3 Answers3

69

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.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • 2
    I thought that _uniform initialization_ usually referred to the _list-initialization_ form (i.e. without the `=`)? I couldn't find a reference for uniform initialization in the standard. – CB Bailey Dec 17 '11 at 12:18
  • @BjörnPollex It would not be a bad thing to re-mention, I think. – cjcurrie Feb 05 '13 at 08:46
0

In my experience, we must set the array size of data and it must be at least as big as the actual initializer list :

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

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Gy_Fk
  • 1
-3

The below program performs initialization of structure variable. It creates an array of structure pointer.

struct stud {
    int id;
    string name;
    stud(int id,string name) {
        this->id = id;
        this->name = name;
    }
    void getDetails() {
        cout << this->id<<endl;
        cout << this->name << endl;
    }
};

 int main() {
    stud *s[2];
    int id;
    string name;
    for (int i = 0; i < 2; i++) {
        cout << "enter id" << endl;
        cin >> id;
        cout << "enter name" << endl;
        cin >> name;
        s[i] = new stud(id, name);
        s[i]->getDetails();
    }
    cin.get();
    return 0;
}