c++arraysc++11initializationdevkitpro

Simpler way to set multiple array slots to one value


I'm coding in C++, and I have the following code:

int array[30];
array[9] = 1;
array[5] = 1;
array[14] = 1;

array[8] = 2;
array[15] = 2;
array[23] = 2;
array[12] = 2;
//...

Is there a way to initialize the array similar to the following?

int array[30];
array[9,5,14] = 1;
array[8,15,23,12] = 2;
//...

Note: In the actual code, there can be up to 30 slots that need to be set to one value.


Solution

  • This function will help make it less painful.

    void initialize(int * arr, std::initializer_list<std::size_t> list, int value) {
        for (auto i : list) {
            arr[i] = value;
        }
    }
    

    Call it like this.

    initialize(array,{9,5,14},2);