I need to initialize all elements of a std::array
with a constant value, like it can be done with std::vector
.
#include <vector>
#include <array>
int main()
{
std::vector<int> v(10, 7); // OK
std::array<int, 10> a(7); // does not compile, pretty frustrating
}
Is there a way to do this elegantly?
Right now I'm using this:
std::array<int, 10> a;
for (auto & v : a)
v = 7;
but I'd like to avoid using explicit code for the initialisation.
With
std::index_sequence
, you might do:With usage
Which, contrary to
std::fill
solution, handle non default constructible type.You can do as following
Or use
std::fill
from algorithms header file. To include algorithms header file useSince C++17 you can write a constexpr function to efficiently set up the array, since the element accessors are constexpr now. This method will also work for various other schemes of setting up initial values:
The
std::array
type is an aggregate that supports list-initialization:It also supports aggregate-initialization:
This is inconvenient and error-prone for long arrays, and you would be better off using a solution like Jarod42’s for those.
Alas not;
std::array
supports aggregate initialisation but that's not enough here.Fortunately you can use
std::fill
, or evenstd::array<T,N>::fill
, which, from C++20 is elegant as the latter becomesconstexpr
.Reference: https://en.cppreference.com/w/cpp/container/array/fill