I read initializer_list
is for functions taking an unknown number of arguments of a single type. But why do we need it? Why can't we use normal containers instead, like vector
or list
?
I tried the following code, and it works.
#include <iostream>
#include <list>
#include <string>
using namespace std;
void f(const list<string> &slst)
{
for (auto s : slst)
cout << s << endl;
}
int main()
{
f({ "Good", "morning", "!" });
system("pause");
return 0;
}
While your code does not explicitly mention it, you are actually using an initializer_list
in the constructor of list
:
list( std::initializer_list<T> init,
const Allocator& alloc = Allocator() );
Indeed, you are probably more likely to use standard library containers that accept initializer lists in their constructors (e.g. std::vector
, std::list
) than writing functions with std::initializer_list
arguments yourself. Another example in the standard library are aggregation functions like std::min
and std::max
that compute a single value from an arbitrary number of input values.
However, there are cases where you might want to use it for your own functions, e.g. for the constructor of a data structure that you implement yourself, or for your own aggregation function. While these things would also be possible with std::vector
or std::list
, the most straightforward way with the smallest overhead is to use std::initializer_list
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With