I am trying to defined and initialize an array of struct.
#include <iostream>
#include <array>
int main() {
struct row{
double a0;
double a1;
};
//method 0: this way works
row c[2] ={{1.0,2.0},{3.0,4.0}};
//method 1: declare and initialization in same line
//std::array<row, 2> a = { {1.0, 2.0}, {3.0, 4.0} };//error: Excess elements in struct initializer
std::array<row, 2> a = {{ {1.0, 2.0}, {3.0, 4.0} }}; //double brace
//method 2, declare, then initialize in different line
std::array<row, 2> b;
//b = { {1.0, 2.0}, {3.0, 4.0} };//error: No viable overloaded '='
b = { { {1.0, 2.0}, {3.0, 4.0} } }; //double brace
return 0;
}
Now I find double brace works from this post .
Just wondering why do we need extra pair of brace to initialize array of struct?
The literals (without the doubled braces) you are trying to use to initialize/assign your std::array
variables do not match the type of those arrays. You need to explicitly make each of the 'top-level' elements a row
object, like this, for example:
int main()
{
struct row {
double a0;
double a1;
};
std::array<row, 2> a = { row{1.0, 2.0}, row{3.0, 4.0} };
std::array<row, 2> b;
b = { row{1.0, 2.0}, row{3.0, 4.0} };
return 0;
}
This is because, without the double braces, your RHS literals are expected to be objects of the std::array<row,2>
class (unambiguously). However, with the double-braces, you are using aggregate initialization rather than (copy) assignment (as mentioned in the post you link).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.