How to initialize an array std::array with std::initializer_list ?
3 answers
The standard class std::array is an aggregate. From the standard C ++ (23.3.2 Class template array)
2 An array is an aggregate ...
Therefore, it cannot be initialized using the std::initializer_list object. You can only copy values from an object of type std::initializer_list to objects of class std::array . Below is an example of how this can be done.
The following shows how this can be done for a data member of a class.
#include <iostream> #include <array> #include <initializer_list> #include <algorithm> #include <iterator> int main() { struct A { A(std::initializer_list<int> lst) { std::copy(lst.begin(), std::next(lst.begin(), std::min(lst.size(), a.size())), a.begin()); } std::array<int, 5> a; } obj{ 1, 2, 3, 4, 5 }; for (int x : obj.a) std::cout << x << ' '; std::cout << std::endl; } Since the number of initializers for the object std::array may be less than the elements in the object, in order to comply with the standards of the C ++ standard, elements left without initializers are also desirable to initialize. For scalar fundamental types, this is initialization 0.
Therefore, it will be more correct to write the class constructor as follows.
A(std::initializer_list<int> lst) { auto it = std::copy(lst.begin(), std::next(lst.begin(), std::min(lst.size(), a.size())), a.begin()); std::fill(it, a.end(), 0); } adding a call to the std::fill algorithm
Honestly, the goal is not entirely clear ... You can then fill it out. If you want a single operator, you can use the lambda:
#include <iostream> #include <array> int main() { std::initializer_list<int> Init = {1,2,3,4,5,6}; // вариант 1 std::array<int,6> Array1; std::copy(Init.begin(),Init.end(),Array1.begin()); // вариант 2 std::array<int, 6> Array2 = [&]() { std::array<int, 6> Values = { 0 }; std::copy(Init.begin(),Init.end(),Values.begin()); return Values; }(); for(const auto &i:Array1) std::cout << i << " "; std::cout << std::endl; for(const auto &i:Array2) std::cout << i << " "; std::cout << std::endl; return 0; } Only for the sake of jokes. To initialize std::array using std::initializer_list you need std::array contain std::initializer_list :
#include <iostream> #include <array> int main() { std::array<std::initializer_list<int>, 2> a = { { { 1, 2, 3 }, { 4, 5, 6 } } }; for( auto e : a ) { for( auto i: e ) { std::cout << i << " "; } std::cout << "\n"; } }