Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simpler way to set multiple array slots to one value

Tags:

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.

like image 735
Matthew D. Scholefield Avatar asked Oct 04 '13 00:10

Matthew D. Scholefield


1 Answers

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); 
like image 98
aaronman Avatar answered Oct 04 '22 23:10

aaronman