c++c++11vectorinitializationinitializer-list

Initializer list vs. vector


In C++11, one can use initializer lists to initialize parameters in functions. What is the purpose of it? Can't the same be done with const vectors? What is the difference of the two programs below?

Using an initializer list:

#include <iostream>

using namespace std;

int sumL(initializer_list<int> l){
    int sum = 0;
    for (const auto i: l){
        sum += i;
    }
    return sum;
}

int main(){

    cout << sumL({1, 2, 3}) << "\n";

    return 0;
}

Using a const vector:

#include <iostream>
#include <vector>

using namespace std;

int sumV(const vector<int> l){
    int sum = 0;
    for (const auto i: l){
        sum += i;
    }
    return sum;
}

int main(){

    cout << sumV({1, 2, 3}) << "\n";
    return 0;
}

Solution

  • The common use of std::initializer_list is as argument to constructors of container (and similar) classes, allowing convenient initialisation of those containers from a few objects of the same type. Of course, you can use std::initializer_list otherwise and then use the same {} syntax.

    Since a std::initializer_list has a fixed size, it doesn't require dynamic allocation and hence can be efficiently implemented. A std::vector, on the other hand, requires dynamic memory allocation. Even in your simple example it is unlikely that the compiler will optimize this overhead away (avoid the intermediary std::vector and its dynamic memory allocation). Other than that, there is no difference in the outcome of your programs (though you should take a const std::vector<int>& argument to avoid a copy and its associated dynamic memory allocation).