大一小白,求大神给解决一个c++题
输入n个数(n<=100),对这n个数进行奇偶识别,使得所有偶数放在数组的左端,所有奇数放在数组的右端(不要求奇数、偶数有序)。要求:编写子函数,完成上述功能,n的值及n个数均在主函数中输入,并在主函数中输出处理结果。解题思路:
1、新建两个数组分别放原数组中的奇数和偶数。
2、将奇数数组中的数复制给原数组
3、将偶数数组中的数复制到原数组奇数的后边
程序代码:#include<iostream>
using namespace std;
const int n=10;//定义常变量n更方便改变数组长度
#include<iomanip>
void h(int a[n]);
void main()
{
int i,a[n];
for(i=0;i<n;i++)
cin>>a[i];
h(a);//将数组首地址作为参数
for(i=0;i<n;i++)
cout<<setw(5)<<a[i];
}
void h(int a[n])
{
int b[n],c[n],i,j,k;//n个数中最多有n个偶数n个奇数
for(i=0,j=0,k=0;i<n;i++)
{
if(a[i]%2==0)//判别偶数
{
b[j]=a[i];
j++;//计数器:记录偶数的个数
}
else
{
c[k]=a[i];
k++;
}
}
i=0;
while(i<j)
{
a[i]=b[i];//先将偶数复制给数组;
i++;
}
k=0;
while(i<n)
{
a[i]=c[k];//再将奇数复制给数组
k++;
i++;
}
}
程序代码:#include <iostream>
using namespace std;
void h( int a[], size_t n );
int main( void )
{
size_t n;
int a[100];
cin >> n;
for( size_t i=0; i!=n; ++i )
cin >> a[i];
h( a, n );
for( size_t i=0; i!=n; ++i )
cout << a[i] << ' ';
cout << endl;
}
void h( int a[], size_t n )
{
size_t even_n=0, odd_n=0;
int even[100], odd[100];
for( size_t i=0; i!=n; ++i )
{
if( a[i]%2 == 0 )
even[even_n++] = a[i];
else
odd[odd_n++] = a[i];
}
for( size_t i=0; i!=even_n; ++i )
a[i] = even[i];
for( size_t i=0; i!=odd_n; ++i )
a[even_n+i] = odd[i];
}
程序代码:#include <iostream>
#include <vector>
#include <iterator>
#include <functional>
#include <algorithm>
using namespace std;
int main( void )
{
vector<int> arr;
// 输入
size_t n;
cin >> n;
copy_n( istream_iterator<int>(cin), n, back_inserter(arr) );
// 排序
std::stable_sort( begin(arr), end(arr), [](int a, int b){ return a%2==0 && b%2==1; } );
// 输出
copy( begin(arr), end(arr), ostream_iterator<int>(cout," ") );
cout << endl;
}