What to do to initialize an array of structure

I use below to initialize an array of CandyBar structures, but the compiler always talks about redundant elements in the structure initializer. I tried to put only one structure initializer in the array definition, it was compiled, but the remaining 2 elements of the array are zero. What should I do?

struct CandyBar{ string brand; float weight; int calories; }; int main(int argc, const char * argv[]) { array<CandyBar, 3> ary_cb = { {"Mocha Munch", 2.3, 350}, {"Mocha Munch", 2.3, 350}, {"Mocha Munch", 2.3, 350} }; return 0; } 
+5
source share
3 answers

You are missing a pair of curly braces around your structures (remember, std::array is a structure containing an array):

  array<CandyBar, 3> ary_cb = { { {"Mocha Munch", 2.3, 350} , {"Mocha Munch", 2.3, 350} , {"Mocha Munch", 2.3, 350} } }; 
+5
source

The reason that the other 2 elements of the array are equal to zero is because you put all the information in the first element of the monoblock, and not the other two elements of the monoblock.

Decision:

 int main(int argc, const char * argv[]) { array<CandyBar, 3> ary_cb = { { //Struct {"Mocha Munch", 2.3, 350}, {"Mocha Munch", 2.3, 350}, {"Mocha Munch", 2.3, 350} } }; return 0; } 

Source → Link

+1
source

Like the quantum suggestion, this also works (in C ++ 11):

 array<CandyBar, 3> ary_cb = { "Mocha Munch", 2.3, 350 , "Mocha Munch", 2.3, 350 , "Mocha Munch", 2.3, 350 }; 

When initializing a nested set of aggregates (i.e., structure / array), you need to leave either all curly braces or not.

0
source

Source: https://habr.com/ru/post/1209416/


All Articles