Static array initialization of individual elements

2019-01-28 13:19发布

问题:

The following code works with GCC's C compiler, but not with the C++ compiler. Is there a "shortcut" to achieve the same result in C++?

int array[10] = {
    [1] = 1,
    [2] = 2,
    [9] = 9
};

EDIT: Humm, I found this, clarifies everything. http://eli.thegreenplace.net/2011/02/15/array-initialization-with-enum-indices-in-c-but-not-c/

回答1:

This form of initialization is only defined in the C99 standard. It does not apply to C++. So, you'll have to assign your elements one-by-one:

int array[10] = { 0 };
array[1] = 1;
array[2] = 2;
array[9] = 9;


回答2:

While gcc may support some sort of extension to C++, it is generally advisable to avoid compiler- and platform-specific extensions wherever possible.

Use the standard C++ syntax for array initialization:

int array[10] = { 0, 1, 2, 0, 0, 0, 0, 0, 0, 9 };

Or write a function to do the initialization of specific elements:

std::array<int, 10> create_initialized_array()
{
    std::array<int, 10> values = { 0 };
    values[1] = 1;
    values[2] = 2;
    values[9] = 9;
    return values;
}

std::array<int, 10> array = create_initialized_array();

Or use a lambda expression:

std::array<int, 10> array = ([]() -> std::array<int, 10>
{
    std::array<int, 10> values = { 0 };
    values[1] = 1;
    values[2] = 2;
    values[9] = 9;
    return values;
})();