C++ Logo

std-discussion

Advanced search

Re: Default array initialization

From: Brian Bi <bbi5291_at_[hidden]>
Date: Wed, 17 Jul 2019 10:59:06 -0500
You can hack it together with integer sequences:
https://stackoverflow.com/a/46899787/481267
Replace `make_foo()` with whatever initial value you want.

On Wed, Jul 17, 2019 at 10:51 AM Joey Pendergrast via Std-Discussion <
std-discussion_at_[hidden]> wrote:

> 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 mailing list
> Std-Discussion_at_[hidden]
> http://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>


-- 
*Brian Bi*

Received on 2019-07-17 11:01:14