我如何在数组中隔离奇数甚至数字
How do I segregate odd and even numbers in an array?
我试图将数组中的奇数隔离,甚至数字。但是,它似乎不起作用。这是我到目前为止编写该功能的方法。它只有在我放入偶数输入的情况下才起作用。例如,如果我输入{1,2,3,4,5,6}作为输入,则它将我作为输出给我{1,5,3,6,2,4}作为输出给我一些随机输出。代码有什么问题?
edit1:我是C 的初学者。
void segregateEvenOdd() {
for (int i = 0; i < endofarray; i++){
int temp;
if (array[i] % 2 == 0) //check if the number is odd or even
temp = array[i];
for(int j = i; j <= endofarray; j++){ //start from 1 cuz we dont want to touch the numbers that are already segregated
array[j] = array[j+1];
}
array[endofarray] = temp;
}
}
实际上有一个标准算法:
#include <algorithm>
#include <ciso646>
#include <cmath>
#include <iostream>
#include <iterator>
int main()
{
int xs[] = { -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 };
std::stable_partition( std::begin(xs), std::end(xs), []( int x )
{
return x and ((std::abs(x) % 2) == 0);
} );
for (int x : xs) std::cout << x << " ";
std::cout << "n";
}
这将使您正确订购:
-4 -2 2 4 -5 -3 -1 0 1 3 5
如果相对顺序无关紧要,请使用std::partition()
。
如果您希望将零视为平均值,请调整条件。
始终小心以正确处理条件。
您的方式非常低效。我建议您执行以下操作:1)创建两个列表(std :: list):一个用于奇数,一个用于偶数数字2)迭代阵列并填充odd_nums和even_nums列表3)浏览odd_nums列表,然后浏览even_nums列表,然后覆盖原始数组的内容。这需要O(n)内存,但是非常快。
这是您可以使用std::vector
和库算法进行操作的方法,因为在C 中,通常最好使用库库容器,例如std::vector
'S,而不是原始数组,因为它们通常是更安全,与标准库的设计更兼容,并且具有有效增长的动态大小:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> iVec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::sort(iVec.begin(), iVec.end(), [](int a, int b) { return (b & 1) && !(a & 1); });
return 0;
}
它将对矢量进行排序,以便甚至在上半场,下半场奇数。印刷时:
std::copy(iVec.begin(), iVec.end(), std::ostream_iterator<int>(std::cout, " "));
输出为:
0 2 4 6 8 10 1 3 5 7 9
如果您希望奇数数首先出现,则可以简单地在谓词(b & 1) && !(a & 1)
中交换a
和b
的位置。谓词基本上检查b是否奇数且A不是A,并且将其结果传递给std::sort
算法,该算法将对此后的元素进行排序。
之后您想将均匀数和奇数划分为单独的容器,则可以使用find_if
算法查找第一个奇数数字,并从给定范围内构造两个向量:
auto it = std::find_if(iVec.begin(), iVec.end(), [](int a) { return (a & 1); });
std::vector<int> evenNumbers(iVec.begin(), it);
std::vector<int> oddNumbers(it, iVec.end());
将产生一个具有均匀数的向量,一个奇数。
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 带内存和隔离功能的SQLite
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 我如何在数组中隔离奇数甚至数字