组合两个数组元素或将一个数组元素分发到另一个数组元素
Combining two arrays elements or distributing one arrays elements to another?
我想将数组 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;
}
我认为不需要neg
、pos
和ab
数组来解决以您所描述的形式重新排列数据的问题。
由于这是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
数组仅重新排列和更改。
相关文章:
- 数组元素打印的递归方法
- 在c++中为double类型的数组创建一个unique_ptr
- 从数组构造一个跨度<shared_ptr<T>><shared_ptr<void>>
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 为什么我的数组输出一个不在其中的元素
- 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?
- 试图为命名数组元素创建一个更好的循环
- 我已经编写了一个代码来查找数组元素的反向,但它没有给出所需的输出
- C++,为什么多维数组的一个元素的增加似乎增加了另一个元素
- 将数组的一个元素与整个数组元素进行比较
- 使用for循环将char数组的一个元素复制到另一个元素
- 将二维数组元素复制到另一个具有其他大小的二维数组中
- 在函数中定义一个动态数组,然后返回数组元素。如何释放阵列的内存?
- 将两个单词读入一个char数组元素
- 连接一个char 2D数组元素和c++中的int
- 输出一个赋值给c++双精度数组元素的字符串
- 读出数组元素会返回一个奇怪的数字;