Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: array<> too many initializers

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}};
like image 315
notaorb Avatar asked Mar 06 '26 06:03

notaorb


1 Answers

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.

like image 117
Arthur Tacca Avatar answered Mar 07 '26 20:03

Arthur Tacca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!