Tilak_Chad
Tilak_Chad

Reputation: 111

Vector of (Structs having vector)

The following piece of code as stated in Bjarne Stroustroup's C++: Programming and Principles

struct Day {
    vector <double> hour { vector <double> (24,-7777)}
};
struct Month {
    vector <Day> day {32};
};

This piece of code initializes 32 days, each day as a vector of 24 hours initialized with -7777;

The question is why list initializer {32} creates 32 days. Isn't it supposed to initialize day vector with 32 as a initial value instead of creating 32 members?

Upvotes: 1

Views: 84

Answers (2)

songyuanyao
songyuanyao

Reputation: 173044

For list initialiation,

Otherwise, the constructors of T are considered, in two phases:

All constructors that take std::initializer_list as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of type std::initializer_list

If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed. If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all).

day is of type vector <Day>, whose constructor taking std::initializer_list as parameter expects an std::initializer_list<Day>, which can't be constructed from the braced-initializer {32}. Then the constructor taking size_type is used and construct the vector with 32 default-inserted instances of Day.

On the other hand, if Day could be initialized from an int, e.g. has a constructor taking int, then std::initializer_list<Day> could be constructed from {32} because of the implicit conversion from int to Day, then vector <Day> day {32}; would construct the vector with one element initialized from 32.

LIVE

Upvotes: 2

acraig5075
acraig5075

Reputation: 10756

The one parameter initializer list is matched to the vector constructor taking one parameter, which allocates that many elements. In this case 32.

Upvotes: 0

Related Questions