我是靠谱客的博主 妩媚大门,这篇文章主要介绍函数对象的使用,现在分享给大家,希望可以做个参考。

一、使用一般的函数调用方法,代码如下:

#include <vector>
#include <string>
#include <iostream>
#include <cstring>
using namespace std;

template<typename Object, typename Comparator>
const Object &findMax(const vector<Object> &arr, Comparator cmp)
{
	int maxIndex = 0;
	
	for(int i = 1; i < arr.size(); ++i)
		if(cmp.isLessThan(arr[maxIndex], arr[i]))
			maxIndex = i;
		
	return arr[maxIndex];
}

class CaseInsensitiveCompare
{
public:
	bool isLessThan(const string &lhs, const string &rhs) const
	{
		return stricmp(lhs.c_str(), rhs.c_str()) < 0;
	}
};

int main()
{
	vector<string> arr(3);
	arr[0] = "ZEBRA";
	arr[1] = "alligator";
	arr[2] = "crocodile";
	
	cout << findMax(arr, CaseInsensitiveCompare()) << endl;
	
	return 0;
}


二、采用函数调用操作符的方式,代码如下:

#include <vector>
#include <string>
#include <iostream>
#include <cstring>
using namespace std;

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];
}

#include <functional>
template<typename Object>
const Object &findMax(const vector<Object> &arr)
{
	return findMax(arr, less<Object>());
}

class CaseInsensitiveCompare
{
public:
	bool operator()(const string &lhs, const string &rhs) const
	{
		return stricmp(lhs.c_str(), rhs.c_str()) < 0;
	}
};

int main()
{
	vector<string> arr(3);
	arr[0] = "ZEBRA";
	arr[1] = "alligator";
	arr[2] = "crocodile";
	
	cout << findMax(arr, CaseInsensitiveCompare()) << endl;
	cout << findMax(arr) << endl;
	
	return 0;
}


最后

以上就是妩媚大门最近收集整理的关于函数对象的使用的全部内容,更多相关函数对象内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(109)

评论列表共有 0 条评论

立即
投稿
返回
顶部