7

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?

Baruch
  • 20,590
  • 28
  • 126
  • 201

1 Answers1

5

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*>>.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Great. But, is this guaranteed to work? Is `std::array` guaranteed to have a C array of type `T[n]` inside? – Aykhan Hagverdili Aug 24 '22 at 12:13
  • I don't understand why #2 is needed. Why does this work `std::array a = {1,2};` with only one set of brackets? – Baruch Aug 24 '22 at 12:18
  • 1
    @AyxanHaqverdili I added a note. – Ted Lyngmo Aug 24 '22 at 12:18
  • Also, why does it work if I explicitly add `std::vector` to only the first initializer? – Baruch Aug 24 '22 at 12:19
  • @AyxanHaqverdili According to the answer in https://stackoverflow.com/questions/53305831/brace-elision-in-stdarraystdvector which I would expect to be trustworthy it is indeed not guaranteed that initialization with braced arguments is possible at all going strictly by the library definition. – user17732522 Aug 24 '22 at 12:33