组合两个数组元素或将一个数组元素分发到另一个数组元素

Combining two arrays elements or distributing one arrays elements to another?

本文关键字:数组元素 一个 另一个 两个 组合      更新时间:2023-10-16

我想将数组 ab[i] 的元素分布到 posi[i](绝对值 + 正数(

ints entered:- [1,2,3,4,5,-6,-7,-8,-9, 0(to quit)]
posi[i] = [1,2,3,4,5]
av[i] = [9,8,7,6] since I've reversed them

然后,新阵列应[1,2,3,4,5,9,8,7,6][1,2,3,4,5,6,7,8,9]

这是我到目前为止所做的:

#include <iostream>
using namespace std;
const int sentinel=0;
const int arraysize=20;
int main()
{
    int numbers[arraysize];
    int neg[arraysize];
    int posi[arraysize];
    int ab[arraysize];
    int count=0;
    int negcount=0;
    int posicount=0;
    int absolutecount=0;
    int absolute;
    int num;
    cout << "Enter ints -0 to quit: ";
    cin >> num;
    while (num != sentinel && count < arraysize)
    {
        numbers[count] = num;
        cin >> num;
     }
    //   Negative
    for (int i=0; i < count; i++)
    if ( numbers[i] < 0)
    {
        neg[negcount]=numbers[i];
        negcount++;
    }
    cout << "Absolute value: ";
    for (int i= negcount-1; i >= 0;i--)
    {
        absolute = neg[i]*-1;
        ab[i] =absolute;
        cout << ab[i] << ' ';
    }
    cout << endl;
    //   Negative
    for (int i=0; i < count; i++)
    if ( numbers[i] > 0)
    {
        posi[posicount] = numbers[i];
        posicount++;
    }
    cout << "Positive Number: ";
    for ( int i=0; i<posicount; i++)
        cout << posi[i] << ' ';
    cout << endl;
    return 0;
} 

我认为不需要negposab数组来解决以您所描述的形式重新排列数据的问题。

由于这是C++,让我们使用一些 STL 算法函数:

#include <iostream>
#include <algorithm>
int main()
{
    int numbers[] = {1,2,3,4,5,-6,-7,-8,-9};
    // partition negatives from positive numbers
    auto iter = std::stable_partition(std::begin(numbers), 
                                      std::end(numbers), [](int n)
                                     { return n >= 0; });
    // reverse the negative numbers
    std::reverse(iter, std::end(numbers));
    // make the negative numbers positive
    std::for_each(iter, std::end(numbers), [](int& n){ n *= -1; });
    // output results
    for (auto& i : numbers)
      std::cout << i << " ";
}

使用的功能:

标准::stable_partition

标准::反向

标准::for_each

现场示例

请注意,不需要辅助阵列来解决问题。 numbers数组仅重新排列和更改。