Kostas
Kostas

Reputation: 4176

Initializing std::vector with curly braces uses initializer list

When I replace inner parens with curly braces I get a different result. Why?

Aren't they equivalent after C++11? (apart from preventing integer demotion) Why does it change construction:

from std::vector(size_type count, const T& value = T(), const Allocator& alloc = Allocator());

to std::vector(std::initializer_list<T> init, const Allocator& alloc = Allocator());

EXAMPLE

auto th_buckets = std::vector<std::vector<int>>{2, std::vector<int>(5, 0)};

0 0 0 0 0

0 0 0 0 0

auto th_buckets = std::vector<std::vector<int>>{2, std::vector<int>{5, 0}};

5 0

5 0

Upvotes: 2

Views: 642

Answers (1)

gct
gct

Reputation: 14563

No they aren't the same, if a class has a constructor taking a std::initializer_list, that is preferentially called even if another constructor would fit the initialization list. std::vector does have one, so the second example creates a list containing [5,0] whereas the second one contains a list of [0,0,0,0,0].

It's generally accepted they messed this part up, sorry!

Upvotes: 2

Related Questions