【发布时间】:2020-11-26 11:24:17
【问题描述】:
假设我有一个包含 10000 个整数的数组,它将被拆分为 3 个子数组(在本例中为“num_jobs”)。在我的代码中,我找到了每个子数组的长度,长度存储在函数“split()”中的数组“parts”中。
我的代码:
// Function that prints
// the required sequence
int * split(int x, int n) //x=10000,n=3
{
// If we cannot split the
// number into exactly 'N' parts
int *parts;
parts = new int[n];
if(x < n)
{
return parts;
}
// If x % n == 0 then the minimum
// difference is 0 and all
// numbers are x / n
else if (x % n == 0)
{
for(int i=0;i<n;i++)
{
parts[i] = (x/n);
}
}
else
{
// upto n-(x % n) the values
// will be x / n
// after that the values
// will be x / n + 1
int zp = n - (x % n);
int pp = x/n;
for(int i=0;i<n;i++)
{
if(i>= zp)
parts[i] = (pp + 1);
else
parts[i] = pp;
}
}
// cout<<parts[0]<<parts[1]<<parts[2];
return parts;
}
main()
{
int num_jobs;
cout << "Enter Number of Jobs: "; // Type a number and press enter
cin >> num_jobs; // Get user input from the keyboard
int sizeOfInputArray = 10000;
int* partsArray = split(sizeOfInputArray, num_jobs);
for(int index=0;index<num_jobs;index++)
{
cout<<partsArray[index];
}
}
我要做的是创建 num_jobs 个数组,每个长度都存在于“partsArray”中。对于 10000 长度,给定 3 个 num_jobs,它返回一个包含 3333、3333、3334 的数组,它表示每个子数组的大小。如何处理 10000 长度的大数组的拆分?
【问题讨论】:
-
(1) 你需要使用c-arrays吗?在 C++ 中,您应该使用
std::vector。 (2)如果n没有精确划分初始大小,你想如何分配“剩余”元素? -
1.创建
n容器。 2. 遍历您的数组并将元素i放入容器i*n/10000。
标签: c++ arrays split dynamic-arrays