Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a std::array with a constant value

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.

like image 293
Jabberwocky Avatar asked Sep 02 '19 11:09

Jabberwocky


1 Answers

With std::index_sequence, you might do:

namespace detail {     template <typename T, std::size_t ... Is>     constexpr std::array<T, sizeof...(Is)>     create_array(T value, std::index_sequence<Is...>)     {         // cast Is to void to remove the warning: unused value         return {{(static_cast<void>(Is), value)...}};     } }  template <std::size_t N, typename T> constexpr std::array<T, N> create_array(const T& value) {     return detail::create_array(value, std::make_index_sequence<N>()); } 

With usage

auto a = create_array<10 /*, int*/>(7); // auto is std::array<int, 10> 

Which, contrary to std::fill solution, handle non default constructible type.

like image 145
Jarod42 Avatar answered Sep 26 '22 03:09

Jarod42