Specify element position in array declaration in C ++

In C, it is often useful to indicate the position of an element when performing an array declaration.

eg:

int appliance_id_from_mode[] = { [MASTER] = 0, [SLAVE] = 1 }; 

This declaration literally doesn't work in C ++ (or at least g ++), is there any equivalent?

+4
source share
5 answers

Does this look like use for a card?

 std:map<??, int> apl_id_mode; mode[MASTER] = 0; mode[SLAVE] = 1; 
+4
source

This is not supported in C ++, you can expand this into equivalent declarations:

 int appliance_id_from_mode[ (MASTER > SLAVE? MASTER : SLAVE) + 1 ] = {}; appliance_id_from_mode[ MASTER ] = 0; appliance_id_from_mode[ SLAVE ] = 1; 

Not quite beautiful ... but it should work. If MASTER and SLAVE are enumeration values, you can create a third entry NUMBER_OF_MODES, which avoids the need for cumbersome calculation of the size of the array size ...

+1
source
 enum { MASTER = 0, SLAVE = 1 }; 
0
source

Do not think that such a language equivalent exists (at least) in standard C ++. However, for ease of reading, you can certainly use the service /*comments*/ !

 int appliance_id_from_mode[] = { /* MASTER */ 0, /* SLAVE */ 1 }; 
-1
source

C # has such luxury . By default, we (C ++ programmers) do not have that luxury under C ++. IMO, just accept it and take the pain, rather than create confusing code using other means instead of simple arrays.

-1
source

All Articles