12

The following code is returning the compilation error below. I'm stuck understanding how there are too many initializers. This code works using vector<X>. Does anyone know why the error is being reported and how to resolve? Thanks

#include <iostream>
#include <array>
using namespace std;

struct X {
    int x, y;
};

int main(int argc, char *argv[])
{
    array<X,2> a0 = {{0,1}, {2,3}};

    for (auto& p : a0) {
        cout << p.x << endl;
        cout << p.y << endl;
    }

    return 0;
}

Compilation:

g++ -pedantic -Wall test116.cc && ./a.out
test116.cc: In function ‘int main(int, char**)’:
test116.cc:11:34: error: too many initializers for ‘std::array<X, 2>’
     array<X,2> a0 = {{0,1}, {2,3}};
3

3 Answers 3

21

Try

array<X,2> a0 = {{{0,1}, {2,3}}};

Note the extra set of braces.

It seems a bit odd but it's this way because the only member of array is the actual array:

template <class T, size_t N>
class array {
    T val[N];
    // ...
};

The constructors are all implicitly defined so that array ends up being a trivially constructable type.

Sign up to request clarification or add additional context in comments.

7 Comments

Why are the extra braces required? Also note, I'm copying this nearly identical to Stroustrup C++ 4th Ed Page 208, which shows no errata.
Sidenote: Brace elision works too: array<X,2> a0 {0, 1, 2, 3}; (although I personally think that makes it hard to read).
@notaorb the language standard for braced initialization keeps changing; it might have been correct at the time of publication!
The implicit construction is similar to struct Z {int x[2];}; and struct Z zz = {{0, 1}};.
Tysm bro. u saved my assignment.
|
7

You may use one of the following initializations because std::array is an aggregate that contains another aggregate as its data member.

array<X,2> a0 = { { { 0, 1 }, { 2, 3 } } };
array<X,2> a0 = { 0, 1, 2, 3 };
array<X,2> a0 = { { 0, 1, 2, 3 } };
array<X,2> a0 = { { 0, 1, { 2, 3 } } };
array<X,2> a0 = { { { 0, 1 }, 2, 3 } };

1 Comment

... and they say C++ is strict :-) Both answers got my vote. Putting names to all the different initialization versions might provide some extra value.
0

I found that my problem is related to the version of g++,9.4.0 is ok and 5.4.0 not.version of g++.By the way, the version of g++ is associated with the system version generally.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.