Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 978
pfnuesel Avatar asked Jan 03 '15 09:01

pfnuesel


People also ask

Can you initialize a vector with initializer list?

Initializer lists are not limited to just normal Vectors, and can be used to initialize multi-dimensional vectors as well.

What is STD initializer list in C++?

std::initializer_listThis type is used to access the values in a C++ initialization list, which is a list of elements of type const T . Notice though that this template class is not implicitly defined and the header <initializer_list> shall be included to access it, even if the type is used implicitly.


2 Answers

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).

like image 128
Walter Avatar answered Oct 02 '22 15:10

Walter


initializer_list uses optimal storage location and prevents unnecessary calls, it's designed to be lightweight, while with vector there's a heap allocation and there may be more copies/moves made.

like image 28
Laura Maftei Avatar answered Oct 02 '22 16:10

Laura Maftei