This C++11 code works fine for me:
#include <iostream>
#include <vector>
#include <array>
using namespace std;
struct str {
int first, last;
};
vector<str> fields {
{1,2}, {3,4}, {5,6}
};
int main()
{
for (str s : fields)
cout << s.first << " " << s.last << endl;
}
It prints the six expected values.
But if I change vector<str>
to array<str,3>
, gcc gives me this error: "too many initializers for ‘std::array’".
If I change the initialization of fields
thus:
array<str,3> fields {
str{1,2}, str{3,4}, str{5,6}
};
Things work nicely.
So why do I need str{1,2}
when using std::array
, but only {1,2}
when using std::vector
?
See cppreference's section on aggregate initialization.
This means that if you had an aggregate inside your struct, such as:
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 instd::array
(for example,T a[N]
).However, you can still initialize your array like this:
or:
instead.
On the other hand, how you initialize your vector is covered by list initialization.
std::vector
has a constructor that accepts anstd::initializer_list
.Note that you wouldn't be able to initialize your vector ( like this:
but:
is perfectly fine.
It's because array initialization is built a bit different from vector.
To initialize an array you need to use two braces.
Because of a syntax feature you can skip it if you initialize just one object.
So the following is ok:
But in your example you initialize multiple objects so the compiler doesn't add additional braces. Using two braces fixes that.