更简单的方法来设置多个阵列插槽,一个值 [英] Simpler way to set multiple array slots to one value

查看:160
本文介绍了更简单的方法来设置多个阵列插槽,一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编码 C ++ ,我有以下的code:

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;
//...

注意:在实际code,可以有多达30个时隙需要被设置为一个值

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

推荐答案

此功能将帮助它那么痛苦。

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;
    }
}

这样称呼它。

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

这篇关于更简单的方法来设置多个阵列插槽,一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆