组合两个数组元素或将一个数组元素分配给另一个?

时间:2017-02-05 01:06:04

标签: c++ arrays

我想将数组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;
} 

1 个答案:

答案 0 :(得分: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 << " ";
}

使用的功能:

std::stable_partition

std::reverse

std::for_each

Live Example

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