Simpler way to set multiple array slots to one value

前端 未结 10 2245
我寻月下人不归
我寻月下人不归 2021-02-18 16:31

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[1         


        
10条回答
  •  粉色の甜心
    2021-02-18 16:59

    This function will help make it less painful.

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

    Call it like this.

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

提交回复
热议问题