[英]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)遍历数组并填充奇数和偶数列表3)遍历奇数列表,然后然后在even_nums列表上,并覆盖原始数组的内容。 这需要O(n)内存,但速度非常快。
这是使用std::vector
和库算法的一种方法,因为在C ++中,通常最好使用std::vector
之类的库容器,而不是原始数组,因为它们通常更安全,并且更兼容具有标准库的设计,并且具有动态增长的大小,可以有效地增长:
#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是否为奇数,然后将其结果传递到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());
它将产生一个带有偶数的向量,以及一个带有奇数的向量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.