Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Initialize an array using initializer-list C++

I have a question related to C++ arrays and structs. I have a struct:

struct npc_next_best_spot{
    npc_next_best_spot(): x({0}),
                          y({0}),
                          value(-1),
                          k(0),
                          i({0}), 
                          triple_ress({0}),
                          triple_number({0}),
                          bigI(0)
    {}

    int x[3]; 
    int y[3]; 
    double value; 
    int k; 
    int i[3]; 
    int triple_ress[3]; 
    int triple_number[3];
    int bigI;
};

but this gives the warning

"list-initializer for non-class type must not be parenthesized".

So how can I make sure that these arrays are initialized with 0 values for all?

like image 588
Adrian Avatar asked Jun 12 '17 13:06

Adrian


Video Answer


2 Answers

You can do as the error suggests. You can use a brace initializer for your arrays like

npc_next_best_spot() : x{}, y{}, value(-1), k(0), i{}, triple_ress{}, triple_number{}, bigI(0) {}

Leaving the list blanks works as any missing initializer will zero initialize the element in the array.

like image 166
NathanOliver Avatar answered Sep 28 '22 10:09

NathanOliver


You can accomplish that by not using the parens at all:

struct npc_next_best_spot{
    npc_next_best_spot(): x{0},
                          y{0},
                          value(-1),
                          k(0),
                          i({0}), 
                          triple_ress({0}),
                          triple_number({0}),
                          bigI(0)
    {} 

Since you are using the uniform initializer it is worth to note that you can initialize to zero an array in multiple ways using a list-initializer:

    int a[3] = {0}; // valid C and C++ way to zero-out a block-scope array
    int a[3] = {}; // invalid C but valid C++ way to zero-out a block-scope array

Note that the previous syntax does not work if you want to set the array to a value c!=0.

int a[3] = {-1} would mean set the first element of a to -1 (just the first one). As another example, int a[5] = { 1, 2 }; will result in 1,2,0,0,0

C++ has a nice set of function for inizialiting containers and something like the following will do the job:

std::fill_n(a, 3, -1);

If your compiler is GCC and you are working in c99 you can also use the following syntax: int a[1024] = {[0 ... 1023] = 5}; to initialize a portion of the array to a value (even though this lead to an increase in the generated code size proportional to the size of the initialized array).

  • Check an exmaple online here
  • More on this here.

I strongly suggest to take a look at this page on array initialization.

and this answer for further details

like image 37
Davide Spataro Avatar answered Sep 28 '22 08:09

Davide Spataro