Sup
Sup

Reputation: 307

Splitting an array into multiple arrays c++

What is the best way to split an array(mainArr) that holds 50 random integers into 5 different arrays that all contain 10 of the integers in each?

For example arr1 holds mainArr's 0-9 values, arr2 holds 10-19....

I have searched around but everything is splitting the array into two different arrays. Any help would be appreciated. Thanks.

Upvotes: 1

Views: 23430

Answers (2)

Jason
Jason

Reputation: 3917

Just define a function that maps each index, 0..49, into another index 0..4. The obvious function is division by 10. Modulus by 5 also works though.

int a[50];
int b[5][10];

for (size_t i = 0; i < 50; i++)
  b[i/10][i%10] = a[i];

or

int a[50];
int b[5][10];

for (size_t i = 0; i < 50; i++)
  b[i%5][i/5] = a[i];

See @nnn's solution for an example that re-uses the same memory.

Upvotes: 0

nnn
nnn

Reputation: 4230

To be a little more generic:

int mainArr[50];
int *arr[5];

int i;
for(i = 0; i < 5; i++)
    arr[i] = &mainArr[i*10];

And then access for example mainArr[10] as arr[1][0].

Upvotes: 3

Related Questions