gpt4 book ai didi

c++ - 将数组的某些元素转移/分离到其他数组

转载 作者:行者123 更新时间:2023-11-28 06:29:01 40 4
gpt4 key购买 nike

假设用户将数字 10、11、22、33、44、55、66、77、88 和 99 输入到数组中。然后程序必须将 50 以下和 50 以上的数字分成两个不同的数组,即 array2 和 array3。但是当我运行我的程序时,它会在 array2 和 array3 中显示一些垃圾内存。

我的程序将与显示器一起运行:

array1 中的数字

10, 11, 22, 33, 44, 55, 66, 77, 88, 99

array2 中的数字

1972394090, 22, 33, 44, 0, 4202032, 2686624, 2686680, 2686924, 10, 11

array3 中的数字

2686700, 4202032, 0, 2686604, 55, 66, 77, 88, 99, 1972394134, 1972394090

这是我的函数代码(N定义为10)

void segArr(int array[N], int array2[N], int array3[N])
{

int i;


for(i=1; i<N; i++)
{
if(array[i]<50)
array2[i]=array[i];
if(array[i]>50)
array3[i]=array[i];
}

return;
}

最佳答案

也许你想做这样的事情:

const int split=50;
int n2=0, n3=0;
for(int i1=0; i1!=n1; ++i1)
if(array1[i1] < split)
array2[n2++] = array1[i1];
else
array3[n3++] = array1[i1];
// n2,n3 now hold the filled sizes of array2 and array3

当然,使用 std 容器可以更好地完成所有这些……特别是,您可能对 std::partition 感兴趣或 std::stable_partition ,重新排列数组/容器中的顺序或元素。

关于c++ - 将数组的某些元素转移/分离到其他数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27980345/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com