题目:
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;
}