Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use initializer_list in C++11?

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;
}
like image 229
Sean Avatar asked Sep 15 '16 13:09

Sean


1 Answers

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.

like image 70
ValarDohaeris Avatar answered Oct 23 '22 04:10

ValarDohaeris