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;
}
Initializer lists are not limited to just normal Vectors, and can be used to initialize multi-dimensional vectors as well.
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.
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).
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.
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