What is the actual benefit and purpose of initializer_list
, for unknown number of parameters? Why not just use vector
and be done with it?
In f
The biggest advantage of initializer_list
over vector
is that it allows you to specify in-place a certain sequence of elements without requiring dedicate processing to create that list.
This saves you from setting up several calls to push_back
(or a for
cycle) for initializing a vector
even though you know exactly which elements are going to be pushed into the vector.
In fact, vector
itself has a constructor accepting an initializer_list
for more convenient initialization. I would say the two containers are complementary.
// v is constructed by passing an initializer_list in input
std::vector v = {"hello", "cruel", "world"};
Of course it is important to be aware of the fact that initializer_list
does have some limitations (narrowing conversions are not allowed) which may make it inappropriate or impossible to use in some cases.