#include<iostream>
#include<vector>
#include<string>
#include<iterator>
#include<stdlib.h>
#include<time.h>
using namespace std;
template<class T>
class LessThan
{
public:
virtual bool operator()(const T& one,const T& other)=0;
};
template<class T>
class LessThanOfIntDoubleString:public LessThan<T> //针对整数,浮点数和字符串
{
public:
bool operator()(const T& one,const T& other)
{
return one<other;
}
};
template<class T,class Iterator>
void max(const Iterator& beg,const Iterator& end,LessThan<T>& lessthan,T& Maxvalue)
{
Maxvalue=*beg;
Iterator it;
for(it=beg;it!=end;it++)
{
if(*it>Maxvalue) Maxvalue=*it;
}
}
void main()
{
const int n=100;
vector<int>a;
int i;
srand((unsigned)time(0));
for(i=0;i<n;i++)
{
a.push_back(rand()%n);
cout<<a[i]<<" ";
}
cout<<endl;
int Maxvalue;
max(a.begin(),a.end(),LessThanOfIntDoubleString<int>(),Maxvalue);
cout<<"最大值是:"<<Maxvalue<<endl;
}
模板泛型求最大值
本文介绍了一个使用C++模板泛型实现的寻找容器中最大值的方法。该方法通过定义泛型比较类来适应整数、浮点数及字符串等多种数据类型,并演示了如何在整数向量中找到最大值。
1747

被折叠的 条评论
为什么被折叠?



