简体   繁体   English

将数组拆分为多个数组C ++

[英]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? 将拥有50个随机整数的array(mainArr)拆分成5个不同的数组(每个数组均包含10个整数)的最佳方法是什么?

For example arr1 holds mainArr's 0-9 values, arr2 holds 10-19.... 例如arr1保留mainArr的0-9值,arr2保留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] . 然后将mainArr[10]作为arr[1][0]

Just define a function that maps each index, 0..49, into another index 0..4. 只需定义一个将每个索引0..49映射到另一个索引0..4的函数即可。 The obvious function is division by 10. Modulus by 5 also works though. 明显的功能是除以10。但是,以5为模也可以。

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. 有关重复使用相同内存的示例,请参见@nnn解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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