【essential c++】模板函数编程练习2_5

题目:


1.没有使用模板函数时,很麻烦,贴出来主要是要注意对于向量的使用,初始化。先定义数组,字符串数组之类的,然后用数组进行初始化,还有const形参和引用的问题,引用是为了传址,避免复制时耗费时间,而const则是为了保护变量,防止被修改。

/*inline int max(int t1,int t2)
{
	return t1 > t2 ? t1 : t2 ;
}

inline float max(float t1,float t2)
{
	return t1 > t2 ? t1 : t2 ;
}

inline string max(const string &t1,const string &t2)//意思是复制地址,更快捷,但又不想被改变
{
	return t1 > t2 ? t1 : t2 ;
}

inline int max(const vector<int> &vec )
{
	return * max_element(vec.begin(),vec.end()) ;
}

inline float max(const vector<float> &vec )
{
	return * max_element(vec.begin(),vec.end()) ;
}

inline string max(const vector<string> &vec )
{
	return * max_element(vec.begin(),vec.end()) ;
}

//一个整数数组
inline int max(const int *array,int size )
{
	return * max_element(array,array+size) ;
}

inline float max(const float *array,int size )
{
	return * max_element(array,array+size) ;
}
inline string max(const string *array,int size )
{
	return * max_element(array,array+size) ;
}

*/
2.这是使用模板后的,中间遇到的问题是,max与STL中的max重复了,导致一直重载不成功。

max_element(vec.begin(),vec.end();可取最大值

还有数组元素的表示,array+6表示,第7个元素(a[0]是第一个咯)


template<typename T>
inline T max1(T t1,T t2)
{
	return t1 > t2 ? t1 : t2 ;
}

template<typename T>
inline T max1(const vector<T> &vec)
{
	return * max_element(vec.begin(),vec.end()) ;
}

template<typename T>
inline T max1(const T *array,int size )
{
	return * max_element(array,array+size) ;
}





int main()
{
	string sarry [] ={"we","were","her","pride","of","ten"};
	vector<string> svec(sarry,sarry+6);

	int iarry[] = {1,4,56,78,98,5,45};
	vector<int>ivec(iarry,iarry+7);

	float farry[] = {2.3,6.8,6.8,4.2,45.4};
	vector<float>fvec(farry,farry+5);


	int imax = max1(max1(ivec),max1(iarry,7));
	float fmax = max1(max1(fvec),max1(farry,5));
	string smax = max1(max1(svec),max1(sarry,6));


	cout << "imax:98   " << imax << endl;
	cout << "fmax:45.4    " << fmax <<endl;
	cout << "smax:were    " << smax <<endl;

	system("pause");
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值