std::array nested initializer

Viewed 97

Why does this not compile

#include <vector>
#include <array>

std::array<std::vector<const char*>, 2> s = {
  {"abc", "def"},
  {"ghi"}
};

but this does

#include <vector>
#include <array>

std::array<std::vector<const char*>, 2> s = {
  std::vector{"abc", "def"},
  {"ghi"}
};

And if for whatever reason the std::vector is needed for the first one, why not for the second?

1 Answers

You need one extra set of { ... }:

std::array<std::vector<const char*>, 2> s = { // #1
    {                                         // #2
        {"abc", "def"},                       // #3
        {"ghi"}                               // #4
    }
};

An attempt at describing why:

  • The inner initializer lists (#3 and #4) goes to the first and second vector.
  • #2 is for aggreggate initialization of the C style array within std::array. From cppreference: This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member.
  • #1 is for std::array itself.

This

std::array<std::vector<const char*>, 2> s = {
  std::vector{"abc", "def"},
  {"ghi"}
};

works because then the initializer list is deduced to initializer_list<vector<const char*>>.

Related