0

I have a code, I can not understand the {} used for create array object.

#include <iostream>
#include <array>
using namespace std;
int main ()
{
    array<int, 3> a1{1, 2, 3};
    array<int, 3> a2{{1, 2, 3}};
    array<pair<int, int>, 3> a3{{1, 2}, {3, 4}, {5, 6}};  // can not compile
    array<pair<int, int>, 3> a4{{{1, 2}, {3, 4}, {5, 6}}};
    return 0;
}

compile

a3 can not compiled,

error: too many initializers for 'std::array<std::pair<int, int>, 3>'
    8 |     array<pair<int, int>, 3> a3{{1, 2}, {3, 4}, {5, 6}};  // can not compile

My understanding

a1 {1,2,3} I think it is using the initializer list {1,2,3} to create array.

a2 I can not understand the nested {{...}} meaning, It looks strange.

a3, I think it can compile, I think {{1, 2}, {3, 4}, {5, 6}} is a initializer list, and it can used to create array.

a4 I can not understand the nested {{...}} meaning, It looks strange.

Do I understand correct?

Cound you please explain the meaning of the a2,a3,a4? Thanks for your time.

Xu Hui
  • 1,213
  • 1
  • 11
  • 24

0 Answers0