例1:
#include <iostream>
#include <vector>
#include <string>
#include <functional>
using namespace std;
template<typename Obj, typename com>
const Obj & findMax(const vector<Obj> &arr, com cmp)
{
int maxIndex = 0;
int iSize = arr.size();
for (int i = 0; i < iSize; i++)
{
if (cmp.isLessThan(arr[maxIndex], arr[i])) maxIndex = i;
}
return arr[maxIndex];
}
class cas
{
public:
bool isLessThan(const string &lhs, const string &rhs) const
{
return stricmp(lhs.c_str(), rhs.c_str());
}
};
int main()
{
vector<string> arr;
arr.push_back("ZEBRA");
arr.push_back("alligator");
arr.push_back("crocodile");
cout << findMax(arr, cas()) << endl;
return 0;
}
例2:使用默认排序 less<>()
#include <iostream>
#include <vector>
#include <string>
#include <functional>
using namespace std;
template<typename Obj, typename com>
const Obj & findMax(const vector<Obj> &arr, com cmp)
{
int maxIndex = 0;
int iSize = arr.size();
for (int i = 0; i < iSize; i++)
{
if (cmp.isLessThan(arr[maxIndex], arr[i])) maxIndex = i;
}
return arr[maxIndex];
}
template<typename Obj, typename com>
const Obj & findMax2(const vector<Obj> &arr)
{
return findMax(arr, less<Obj>());
}
class cas
{
public:
bool isLessThan(const string &lhs, const string &rhs) const
{
return stricmp(lhs.c_str(), rhs.c_str());
}
};
int main()
{
vector<string> arr;
arr.push_back("ZEBRA");
arr.push_back("alligator");
arr.push_back("crocodile");
cout << findMax(arr, cas()) << endl;
return 0;
}