C++ Logo

STD-DISCUSSION

Advanced search

Subject: Default array initialization
From: Joey Pendergrast (joey.pendergrast_at_[hidden])
Date: 2019-07-17 10:51:03


Is there a way to initialize arrays to a default value? I know it can
be done by manually typing all the values out:

std::array<int, 3> a = { 3,3,3 };
std::array<bool, 3> b = { true, true, true };

However, that gets a little tedious and ugly if the array size gets
much larger. I'm wanting to do something along the lines of:

std::array<int = 2, 3> a { }; // would be created with default values of 3
std::array<int = 2, 100> a1{10, 20}; // would be {10, 20, and 2 for the rest}
std::array<bool = true, 20> b{ }; // would default all values to true
or maybe:
std::array<bool, 20> b{true x 20};

For structs, we can do things like:
struct S
{
    int start = 1;
    int end {5}; //
};
S s1{}; // start = 1, end = 5
S s2{10, 20}; // start = 10, end = 20

And for vectors we can do:
std::vector<int> vec(number_of_elements, default_value);

So, a similar format for arrays might make sense. The exact syntax
isn't really that important to me. I just want to be able to
initialize to a default value that I control. I'm aware that it can
be done in two lines with std::fill, but that's not what I'm asking
for. If there's no way to do this, are there any proposals that would
accomplish something similar?


STD-DISCUSSION list run by herb.sutter at gmail.com

Older Archives on Google Groups