当前位置: 首页 > article >正文

C++ 仿函数

仿函数定义 

 仿函数本质上就是类+operator()

看上去仿佛是函数 实际是类

仿函数比函数更灵活 有自己的数据和成员变量

仿函数可以当作参数传递

仿函数比函数指针执行的更快(大多数情况下)

仿函数可以当作模板使用,因为每个仿函数都拥有自己的类型

仿函数返回值类型是bool数据类型 称为谓词

如果operator接受一个参数  就是一元谓词

接收两个参数就是二元谓词

缺点在于定义的时候需要定义在一个类里面

#include<iostream>
using namespace std;
class Print
{
public:
	int operator()(int a)
	{
		cout << a <<" "<<++count << endl;
		return a;
	}
private:
	int count = 0;
};

//作为参数传递
Print add(Print a)
{
	return a;
}

template<class Brin>
Brin bdd(Brin a)
{
	return a;
}

template<class Crin>
Crin cdd(Crin a)
{
	return a;
}


int main(void)
{
	Print aaa;
	int a = 4;
	aaa(a);
//作为参数传递
	add(aaa);
	bdd<Print>(aaa);
	cdd(aaa);
	return 0;
}

我们在有些情况下 必须要用仿函数

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
		: _year(year)
		, _month(month)
		, _day(day)
	{
	}

	bool operator<(const Date& d)const
	{
		return (_year < d._year) ||
			(_year == d._year && _month < d._month) ||
			(_year == d._year && _month == d._month && _day < d._day);
	}

	bool operator>(const Date& d)const
	{
		return (_year > d._year) ||
			(_year == d._year && _month > d._month) ||
			(_year == d._year && _month == d._month && _day > d._day);
	}

	friend ostream& operator<<(ostream& _cout, const Date& d);
private:
	int _year;
	int _month;
	int _day;
};

struct LessPDate
{
	bool operator()(const Date* p1, const Date* p2)
	{
		return *p1 < *p2;
	}
};

		void test_priority_queue2()
	{

		priority_queue<Date*, vector<Date*>, LessPDate> pq;
		pq.push(new Date(2023, 7, 20));
		pq.push(new Date(2023, 6, 20));
		pq.push(new Date(2023, 8, 20));

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



int main(void)
{
	bit::test_priority_queue2();
	return 0;
}

像这个地方我们对于Date*这个类型

我们不可能去重载操作符

因为Date*是内置类型

但是我每次new的地址的大小是随机的

因此我们在这个地方要根据Date大小去建堆就只能自己写一个仿函数了


http://www.kler.cn/a/532584.html

相关文章:

  • 数据结构(AVL树、B-Tree、B+Tree)
  • Codeforces Round 997 (Div. 2) A~D题解
  • Spring Boot常用注解深度解析:从入门到精通
  • 扩展域并查集 带权并查集
  • 【Linux系统】信号:再谈OS与内核区、信号捕捉、重入函数与 volatile
  • 【Numpy核心编程攻略:Python数据处理、分析详解与科学计算】1.25 视觉风暴:NumPy驱动数据可视化
  • babel-安装和使用
  • sort排序 计数排序 map set C++ 蓝桥杯
  • 实验13 JavaBean(二)
  • ROS-激光雷达-消息包格式-获取激光雷达数据-激光雷达避障
  • RabbitMQ深度探索:前置知识
  • 游戏引擎 Unity - Unity 打开项目、Unity Editor 添加简体中文语言包模块、Unity 项目设置为简体中文
  • 【435. 无重叠区间 中等】
  • K8s 分布式存储后端(K8s Distributed Storage Backend)
  • 基础IOIO
  • PHP 调用 DeepSeek API 完整指南
  • 【字节青训营-7】:初探 Kitex 字节微服务框架(使用ETCD进行服务注册与发现)
  • 机器学习day8
  • sql中奇数、偶数、正则
  • 【L2JMobius】ZGC requires Windows version 1803 or later
  • 宝塔面板端口转发其它端口至MySQL的3306
  • 关于大模型 AGI 应知应会_生在AI发展的时代
  • 51单片机入门_05_LED闪烁(常用的延时方法:软件延时、定时器延时;while循环;unsigned char 可以表示的数字是0~255)
  • 统计满足条件的4位数(信息学奥赛一本通-1077)
  • 【通俗易懂说模型】线性回归(附深度学习、机器学习发展史)
  • 高斯过程处理大型数据集时返回值为 0 的问题