例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)
本文介绍了一种使用C++模板实现的泛型比较函数,该函数可以找到向量中的最大元素,支持自定义比较逻辑。通过实例展示了如何使用自定义比较类和标准库中的less比较器来确定字符串向量中的最大值。
订阅专栏 解锁全文
1万+





