直接上代碼:
using namespace std;
namespace std
{
template<>
struct less<const char *>
{
bool operator()(const char * const __x, const char * const __y) const { return strcmp(__x, __y) < 0; }
};
template<>
struct equal_to<const char *>
{
bool operator()(const char * const __x, const char * const __y) const { return strcmp(__x, __y) == 0; }
};
}
printf("%d\n", "abc" < "bcd");
再擴展一下:
template <typename Object, typename Comparator>
const Object& findMax(const vector<Object> &arr, Comparator isLessThan)
{
int maxIndex = 0;
for (int i=1; i < arr.size(); i++)
{
if (isLessThan(arr[maxIndex], arr[i]))
{
maxIndex = i;
}
}
return arr[maxIndex];
}
template<typename Object>
const Object & findMax(const vector<Object>& arr)
{
return findMax(arr, less<Object>());
}
class CCompare
{
public:
bool operator()(const string& lhs, const string& rhs) const
{
return stricmp(lhs.c_str(), rhs.c_str()) < 0;
}
};
然後就可以這樣用了:
vector<string> arr(3);
arr[0] = "ZEBRA";
arr[1] = "alligator";
arr[2] = "crocodile";
printf("%d\n", findMax(arr, CCompare()));