1

It's possible to initialize c++ vector as below:

vector<int> a(5,0);
vector<int> a{0,0,0,0,0};

But if one write

vector<int> a{5,0};

A vector with 2 elements instead of 5 elements is created, i.e. the constructor of vector taking initializer list as argument is called. But such grammar is also possible:

struct myData {
  int k,v;
}
myData mydata{myk, myv};

So my question is, when I write vector<int> a{5,0}, why the constructor vector(initializer_list L) is called, instead of vector(int k, int v)?

My guess is, if a constructor consuming initializer list exists, it will be called, otherwise the initializer list is regarded as argument list. But I'm not sure about this.

Yiran Wu
  • 25
  • 4
  • 3
    [Your guess is correct](https://en.cppreference.com/w/cpp/language/list_initialization#Explanation). But the example with the structure isn't really revelant, because it's an aggregate initialization, not a constructor call. – HolyBlackCat Aug 20 '21 at 16:49
  • 2
    Useful watching: [The Nightmare of Initialization in C++](https://www.youtube.com/watch?v=7DTlWPgX6zs) – user4581301 Aug 20 '21 at 16:53

0 Answers0