简体   繁体   中英

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?

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.

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).

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

and this answer for further details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM