Reply To: C++ Programming

Forumite Points: 6,320

Another “Helpful” C++ feature that is bound to lead to confusion, this time with vectors.

It is possible to initialize a vector in a number of ways and from C++ 11 that includes a list enclosed in curly braces.

vector<int> V1 {10,20}

That is a vector with two elements of 10 and 20.

You can also initialize a vector with a number of default elements using brackets.

vector<string> V1 (10, “hi”)

That vector has 10 elements and they all have the value “hi”.

So far so good.

However if you attempt to list initialize a vector with braces but supply the wrong type C++ will “helpfully” attempt a value initialization instead.

vector<string> V1 {10, “hi”}

This gets you a vector of 10 hi’s again even though you used curly braces.

It is going to confuse me if no one else 😆