Simpler way to set multiple array slots to one value

前端 未结 10 2272
我寻月下人不归
我寻月下人不归 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 17:12

    The best you can do if your indexes are unrelated is "chaining" the assignments:

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

    However if you have some way to compute your indexes in a deterministic way you could use a loop:

    for (size_t i = 0; i < 3; ++i)
        array[transform_into_index(i)] = 1;
    

    This last example also obviously applies if you have some container where your indexes are stored. So you could well do something like this:

    const std::vector indexes = { 9, 5, 14 };
    for (auto i: indexes)
        array[i] = 1;
    

提交回复
热议问题