samedi 4 janvier 2020

Initializing an std::array with structs [duplicate]

This question already has an answer here:

I'm quite a beginner on C++, was testing std::array and structs on Codeblocks. I'm trying to create an array of structs like so:

#include <iostream>
#include <array>

struct Boy{
    int grade;
    int age;
};

int main()
{
  Boy a[2] { {95, 13},
             {23, 15}};             // This compiles
  std::cout << a[0].grade;          // and prints out 95 as expected


  std::array<Boy, 2> b { {95, 13},  //This doesn't compile, gives error and warning
                         {23, 15}};
  std::cout << b[0].grade; 

  return 0;
}

The std::array line gives the following error message and warning:
warning: missing braces around initializer for 'std::array::value_type {aka Boy}'
error: too many initializers for 'std::array'

I'm can't seem to go forward from here, can someone enlighten me on this?

Aucun commentaire:

Enregistrer un commentaire