48

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.

2
  • 1
    There is no reason why it shouldn't work... (btw that would be .scientist = ...) Have you tried?
    – fge
    Dec 16, 2011 at 13:03
  • @fge Yes, it's called aggregate initialisation and is further explained in detail here
    – pfabri
    Dec 10, 2017 at 11:12

3 Answers 3

70

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.

3
  • 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, 2011 at 12:18
  • @BjörnPollex It would not be a bad thing to re-mention, I think.
    – cjcurrie
    Feb 5, 2013 at 8:46
  • This appears to be a gcc extension. As far as I can make out, it's not standard C++ and is unlikely to work in other compilers. It doesn't work in Visual Studio, anyway.
    – digitig
    Nov 24 at 19: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 } } ;

0
-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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.