本例子为一道面试题的归纳总结,题意为调整数组顺序是的奇数位于偶数前面。
这是一类问题,我们在写代码的时候,要考虑扩展性,如果将题意改为将数组中能被3整除的数调整到不能被3整除的数后面,比如将数组中正整数调整到负数后面之类的一系列问题都可以用一个模式解决,而不用重新写很多重复代码。
如下为3种代码写法,第一种为原始写法,不考虑扩展性。第二种为函数指针写法,第三种使用了函数对象的写法。
/*
* author:janestar
* email:janestar@163.com
*/
#include<iostream>
#include<vector>
using namespace std;
//原始写法,不考虑代码复用
void reOrderArray(vector<int> &array){
size_t size = array.size();
if (size == 0)return;
typedef vector<int>::iterator it;
it pbegin = array.begin();
it pend = array.end()-1;
while (pbegin < pend)
{
//向后移动pbegin,直到指向偶数
while (pbegin < pend&&((*pbegin)&0x1) != 0)
pbegin++;
//向前移动pend,知道指向奇数
while (pbegin < pend && ((*pend)&0x1) == 0)
pend--;
if (pbegin < pend){
int tmp = *pbegin;
*pbegin = *pend;
*pend = tmp;
}
}
}
//定义函数指针
typedef bool(*Fun)(int n);
bool judge_is_odd(int n){
if (n & 0x1 == 0)return false;
else return true;
}
//利用函数指针解耦合
void reOrderArray2(vector<int> &array,Fun fun){
size_t size = array.size();
if (size == 0)return;
typedef vector<int>::iterator it;
it pbegin = array.begin();
it pend = array.end() - 1;
while (pbegin < pend)
{
//向后移动pbegin,直到指向偶数
while (pbegin < pend &&fun(*pbegin))
pbegin++;
//向前移动pend,知道指向奇数
while (pbegin < pend && !fun(*pbegin))
pend--;
if (pbegin < pend){
int tmp = *pbegin;
*pbegin = *pend;
*pend = tmp;
}
}
}
//利用function object 解耦合
struct judge_is_odd_struct
{
bool operator()(int val)
{
if (val & 0x1 == 0)return false;
else return true;
}
};
void reOrderArray3(vector<int> &array, judge_is_odd_struct j){
size_t size = array.size();
if (size == 0)return;
typedef vector<int>::iterator it;
it pbegin = array.begin();
it pend = array.end() - 1;
while (pbegin < pend)
{
//向后移动pbegin,直到指向偶数
while (pbegin < pend &&j(*pbegin))
pbegin++;
//向前移动pend,知道指向奇数
while (pbegin < pend && !j(*pend))
pend--;
if (pbegin < pend){
int tmp = *pbegin;
*pbegin = *pend;
*pend = tmp;
}
}
}
int main(){
int data[] = { 1, 3, 3, 4, 5, 6, 8 };
vector<int>num(data,data+sizeof(data)/sizeof(int));
//reOrderArray(num);
//reOrderArray2(num, judge_is_odd);
judge_is_odd_struct s;
reOrderArray3(num, s);
for (auto x : num){
cout << x << " ";
}
cout << endl;
system("pause");
return 0;
}