See cppreference's section on aggregate initialization.
The effects of aggregate initialization are:
Each array element or non-static class member, in order of array subscript/appearance in the class definition, is copy-initialized from
the corresponding clause of the initializer list.
If the initializer clause is a nested braced-init-list, the corresponding class member is itself an aggregate: aggregate
initialization is recursive.
This means that if you had an aggregate inside your struct, such as:
struct str {
struct asdf
{
int first, last;
} asdf;
};
asdf
would be initialized by the first nested brace-init-list, i.e. { { 1, 2 } }
. The reason why you generally need two pairs of braces is because the nested brace-init-list initializes the underlying aggregate in std::array
(for example, T a[N]
).
However, you can still initialize your array like this:
array<str,3> fields {
1, 2, 3, 4, 5, 6
};
or:
array<str,3> fields { {
1, 2, 3, 4, 5, 6
} };
instead.
On the other hand, how you initialize your vector is covered by list initialization. std::vector
has a constructor that accepts an std::initializer_list
.
The effects of list initialization of an object of type T are:
Note that you wouldn't be able to initialize your vector ( like this:
vector<str> fields {
1,2, 3,4, 5,6
};
but:
vector<int> fields {
1,2, 3,4, 5,6
};
is perfectly fine.