栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++函数对象

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++函数对象

文章目录
  • 函数对象
  • 使用函数对象有什么好处
    • 解决1-函数指针
    • 解决2-函数对象
  • 函数对象堆使用
  • 函数对象set使用

函数对象

把有operator()小括号运算符重载函数的对象,称作为函数对象或者仿函数

使用函数对象有什么好处
template
bool compare(T a, T b)
{
	return a > b;
}
int main()
{
	cout << compare(10, 20) << endl;
	cout << compare('b', 'y') << endl;
}

但是这个函数不灵活,如果要比较小于,如果是库函数,肯定不行。

解决1-函数指针
template
inline bool mygreater(T a, T b)
{
	return a > b;
}
template
inline bool myless(T a, T b)
{
	return a < b;
}
int main()
{
	cout << compare(10, 20, mygreater()) << endl;
	cout << compare(10, 20, myless()) << endl;
	//cout << compare('b', 'y') << endl;

	return 0;
}

但是这样的问题就是,通过函数指针调用函数,是没有办法内联的,效率很低,因为有函数调用开销。

解决2-函数对象
  • 通过函数对象调用operator(),可以省略函数的调用开销,比通过函数指针调用函数(不能通过inline内敛调用)效率高
  • 因为函数对象是用类生成的,所以可以添加相关的成员变量,用来记录函数对象使用时候更多的信息
template
class mygreater
{
public:
	bool operator()(T a, T b) // 二元函数对象
	{
		return a > b;
	}
};
template
class myless
{
public:
	bool operator()(T a, T b) // 二元函数对象
	{
		return a < b;
	}
};

// compare是C++的库函数模板
template
bool compare(T a, T b, Compare comp)
{
	// 通过函数指针调用函数,是没有办法内联的,效率很低,因为有函数调用开销
	return comp(a, b);  // operator()(a, b);
}
int main()
{
	cout << compare(10, 20, mygreater()) << endl;
	cout << compare(10, 20, myless()) << endl;
	//cout << compare('b', 'y') << endl;

	return 0;
}
函数对象堆使用
int main()
{
	priority_queue que1; // vector
	for (int i = 0; i < 10; ++i)
	{
		que1.push(rand() % 100);
	}

	while (!que1.empty())
	{
		cout << que1.top() << " ";
		que1.pop();
	}
	cout << endl;

	using MinHeap = priority_queue, greater>;
	MinHeap que2; // vector
	for (int i = 0; i < 10; ++i)
	{
		que2.push(rand() % 100);
	}

	while (!que2.empty())
	{
		cout << que2.top() << " ";
		que2.pop();
	}
	cout << endl;

	return 0;
}
函数对象set使用
int main()
{
	set> set1;
	for (int i = 0; i < 10; ++i)
	{
		set1.insert(rand() % 100);
	}

	for (int v : set1)
	{
		cout << v << " ";
	}
	cout << endl;

	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/913355.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号