简体   繁体   中英

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.

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] .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM