代码复用学习实例

本例子为一道面试题的归纳总结,题意为调整数组顺序是的奇数位于偶数前面。

这是一类问题,我们在写代码的时候,要考虑扩展性,如果将题意改为将数组中能被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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值