Initializing a std::array with a constant value

std::array fill
std::array constructor
std::array 2d
std::array size
c std::array initialization
std::make_array
std::array copy
std::array find

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:

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.

initialize a const array in a class initializer in C++, Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead. int* a = new int[N]; // fill a class C { const� void printArray(const std::array<int, 5> &n) - const is used here to prevent the compiler from making a copy of the array and this enhances the performance. The passed array will be n in this function as &n is the parameter of the function 'printArray'.

Alas not; std::array supports aggregate initialisation but that's not enough here.

Fortunately you can use std::fill, or even std::array<T,N>::fill, which, from C++20 is elegant as the latter becomes constexpr.

Reference: https://en.cppreference.com/w/cpp/container/array/fill

C++ std::array: declare, initialize, passing std::array to function, std::array is a container that wraps around fixed size arrays. Like arrays, we initialize an std::array by simply assigning it values at the time of declaration. Initializing std::array<T, N>, where T is a non-scalar type and N is the number of elements of type T. If T is a non-scalar type std::array can be initialized in the following ways: struct A { int values[3]; }; // An aggregate type // 1) Using aggregate initialization with brace elision // It works only if T is an aggregate type!

You can do as following

std::array<int, 10> a; 
a.fill(2/*or any other value*/);

Or use std::fill from algorithms header file. To include algorithms header file use

#include <algorithm>

std::array, Sets the initial values of the static variables to a compile-time constant. S::c> a1 ; // OK: S::c is a constant expression // std::array<int, d> a2;� Size of a std::array object is always constant i.e. its 2nd template parameter. However, std::array provides a member function size() to return the size i.e. // Returns the constant size arr.size(); How to access elements in std::array. There are 3 ways to access elements in std::array // Creating and initializing an array of size 10.

Since 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:

#include <array>

template<typename T, size_t N>
constexpr auto make_array(T value) -> std::array<T, N>
{
    std::array<T, N> a{};
    for (auto& x : a)
        x = value;
    return a;
}

int main()
{
    auto arr = make_array<int, 10>(7);
}

Constant initialization, #include <array> int main() { std::array<int, 3> arr; // write values arr.at(0) = 2; to the element at compile-time constant position pos without bounds checking. Initializing std::array<T, N> , where T is a scalar type and N is the number of� Below are some of the different ways in which all elements of an array can be initialized to the same value: Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays.

The std::array type is an aggregate that supports list-initialization:

std::array<int, 10> a{2, 2, 2, 2, 2, 2, 2, 2, 2, 2};

It also supports aggregate-initialization:

std::array<int, 10> a = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2};

This is inconvenient and error-prone for long arrays, and you would be better off using a solution like Jarod42’s for those.

std::array, When an initialization of values is provided for an array, C++ allows the possibility arrays example #include <iostream> using namespace std; int billy [] = {16, 2, 77, 40, We have used "defined constants" (#define) to simplify possible future� Like any other variable in C++, an array starts out with an indeterminate value if you don’t initialize it. The only difference is that unlike a simple variable, which contains only one undetermined value, an array starts out with a whole lot of unknown values: int nScores[100]; // none of the values in nScores // […]

Arrays - C++ Tutorials, MAP_WIDTH (and MAP_HEIGHT ) need to be static in this case: static const int MAP_WIDTH = 10; static const int MAP_HEIGHT = 10; Room� I understand your question like this: you want to initialize a vector to a large number of elements. What's wrong with using push_back() on the vector? If you know the number of elements to be stored (or are sure that it will store less than the next power of 2) you can do this, if you have a vector of pointers of type X (works only with pointers):

Can't initialize array in C++ using const int value?, Five values of type int can be declared as an array without having to declare five number of elementsin the array, must be a constant expression, since arrays are arrays example #include <iostream> using namespace std; int foo [] = {16, 2,� The constant value assigned will be used each time the variable is referenced. The value assigned cannot be modified during program execution. Bjarne Stroustrup's explanation sums it up briefly: A class is typically declared in a header file and a header file is typically included into many translation units.

Arrays, A constexpr variable is used when its value is supposed to be constant throughout a program's execution. The constexpr A constexpr array can be declared and initialized manually through: constexpr int using namespace std;. 3. . 4. std::array is a container that encapsulates fixed size arrays. This container is an aggregate type with the same semantics as a struct holding a C-style array T [N] as its only non-static data member. Unlike a C-style array, it doesn't decay to T * automatically.

Comments
  • Related to Why does std::array not have an constructor that takes a value for the array to be filled with?
  • This is the most elegant solution for my needs. Very similar to the non compiling std::array<int, 10> a(7) which becomes auto a = create_array<10, int>(7) or even auto a = create_array<10>(7)
  • What's the difference of all this to just a method with a foreach inside?
  • @mFeinstein: "contrary to std::fill solution, handle non default constructible type.".
  • So std::fill is a foreach?
  • Your foreach or for-range to set value would be equivalent to what fill will do.
  • Thanks for taking the time to write out the actual code. This is something I don't do often enough: Stack Overflow works best when there are multiple answers to choose from.
  • @Bathsheba no problem mate)
  • @Bathsheba I am writing this from a phone so I haven't seen that you already answered the question
  • I'm glad - you should answer answer a question if you believe you have something to say that, perhaps, hasn't already been said. I think this answer is more useful in some ways than mine.
  • Requires default constructible T though.
  • This is inconvenient and error-prone for any array length.
  • @Jabberwocky The accepted answer is great and I upvoted it. It’s also kind of overkill for an array of three elements. The others don’t work for a constexpr std::array. So this technique is sometimes appropriate.