Search code examples
c++stdarrayaggregate-initialization

Why can't std::array<std::pair<int,int>, 3> be initialized using nested initializer lists, but std::vector<std::pair<int,int>> can?


See this example: https://godbolt.org/z/5PqYWP

How come this array of pairs can't be initialized in the same way as a vector of pairs?

#include <vector>
#include <array>

int main()
{
    std::vector<std::pair<int,int>>    v{{1,2},{3,4},{5,6}}; // succeeds 
    std::array <std::pair<int,int>, 3> a{{1,2},{3,4},{5,6}}; // fails to compile
}

Solution

  • You need to add an outer pair of braces to initialize the std::array<...> object itself:

    std::array <std::pair<int,int>, 3> a{{{1,2},{3,4},{5,6}}};
    

    The outermost pair is for the array object, the second pair is for the aggregate array inside the object. Then the list of elements in the array.