C++ 仿函数(Functor)深度解析:从基础到应用

news2026/5/3 21:36:07
引言在C编程中我们经常需要将“行为”作为参数传递给函数或算法。C语言中我们使用函数指针来实现这一需求。但函数指针有局限性不能携带状态、类型安全性较差。C提供了更优雅的解决方案——仿函数。仿函数Functor是重载了operator()的类对象它可以像普通函数一样被调用但可以携带状态并且支持泛型编程。// 函数指针 vs 仿函数 int add1(int a, int b) { return a b; } // 普通函数 struct Add2 { int operator()(int a, int b) const { // 仿函数 return a b; } }; int main() { // 函数指针调用 int r1 add1(10, 20); // 仿函数调用看起来和函数一样 Add2 add; int r2 add(10, 20); // add.operator()(10, 20) // 匿名对象调用 int r3 Add2()(10, 20); return 0; }今天我将从基础到高级全面讲解C仿函数的概念、使用方法、与Lambda表达式的关系以及在实际开发中的应用。第一部分仿函数的基本概念一、什么是仿函数仿函数是一个行为类似函数的对象。它的本质是重载了operator()运算符的类或结构体。#include iostream using namespace std; // 定义仿函数 struct MyFunctor { // 重载operator() int operator()(int a, int b) const { return a b; } }; int main() { MyFunctor func; // 创建对象 int result func(10, 20); // 像函数一样调用 cout result result endl; // 匿名对象调用 int result2 MyFunctor()(5, 3); cout result2 result2 endl; return 0; }关键理解func(10, 20)本质上是func.operator()(10, 20)的语法糖编译器会将对象加括号的调用转换为成员函数调用二、仿函数与普通函数的对比特性普通函数仿函数调用方式func()obj()状态保持❌ 不支持需静态变量✅ 支持成员变量类型函数类型类类型泛型支持有限✅ 模板化内联优化可能更容易编译器可见定义作为模板参数需要指针类型可直接使用类型三、仿函数的状态保持能力这是仿函数相对于普通函数的最大优势。#include iostream using namespace std; // 普通函数无法保持状态只能用静态变量且全局唯一 int counter_func() { static int count 0; return count; } // 仿函数每个对象独立保持状态 struct Counter { private: int count 0; public: int operator()() { return count; } int getCount() const { return count; } }; int main() { // 普通函数不同调用之间共享同一个静态变量 cout counter_func() endl; // 1 cout counter_func() endl; // 2 // 仿函数每个对象有独立的计数器 Counter c1, c2; cout c1() endl; // 1 cout c1() endl; // 2 cout c2() endl; // 1独立计数 return 0; }应用场景统计函数被调用的次数、累加器、生成唯一ID等。第二部分仿函数的实现方式一、基本实现#include iostream using namespace std; // 无参数仿函数 struct Hello { void operator()() const { cout Hello, World! endl; } }; // 单参数仿函数 struct Square { int operator()(int x) const { return x * x; } }; // 多参数仿函数 struct Add { int operator()(int a, int b) const { return a b; } }; int main() { Hello()(); // 输出Hello, World! Square sq; cout sq(5) endl; // 25 Add add; cout add(10, 20) endl; // 30 return 0; }二、带状态的仿函数#include iostream #include string using namespace std; // 带状态的仿函数记录调用信息 struct Logger { private: string name; int call_count 0; public: Logger(const string n) : name(n) {} void operator()(const string msg) { call_count; cout [ name ] 第 call_count 次调用: msg endl; } int getCount() const { return call_count; } }; int main() { Logger log1(模块A); Logger log2(模块B); log1(初始化完成); log1(处理数据); log2(启动服务); log1(保存结果); cout log1调用次数: log1.getCount() endl; // 3 cout log2调用次数: log2.getCount() endl; // 1 return 0; }三、模板化仿函数泛型仿函数#include iostream using namespace std; // 泛型仿函数支持多种类型 templatetypename T struct Greater { bool operator()(const T a, const T b) const { return a b; } }; templatetypename T struct Less { bool operator()(const T a, const T b) const { return a b; } }; int main() { Greaterint greater_int; cout greater_int(10, 5) endl; // 1 (true) cout greater_int(3, 7) endl; // 0 (false) Greaterstring greater_str; cout greater_str(banana, apple) endl; // 1 (按字典序) Lessdouble less_double; cout less_double(3.14, 2.71) endl; // 0 cout less_double(2.71, 3.14) endl; // 1 return 0; }四、继承标准库仿函数#include iostream #include functional #include string using namespace std; // 继承 std::binary_functionC17前 // C17后可以直接继承但更推荐组合或使用lambda struct CaseInsensitiveLess { bool operator()(const string a, const string b) const { // 不区分大小写的比较 for (size_t i 0; i min(a.size(), b.size()); i) { char ca tolower(a[i]); char cb tolower(b[i]); if (ca ! cb) return ca cb; } return a.size() b.size(); } }; int main() { CaseInsensitiveLess cmp; cout cmp(Apple, apple) endl; // 0相等 cout cmp(apple, Banana) endl; // 1a b return 0; }第三部分仿函数在STL中的应用一、排序中的仿函数STL算法大量使用仿函数作为比较参数。#include iostream #include vector #include algorithm using namespace std; // 升序仿函数 struct Ascending { bool operator()(int a, int b) const { return a b; } }; // 降序仿函数 struct Descending { bool operator()(int a, int b) const { return a b; } }; // 按绝对值排序 struct ByAbs { bool operator()(int a, int b) const { return abs(a) abs(b); } }; int main() { vectorint arr {5, -2, 8, -9, 1, 3, -4}; // 使用自定义仿函数排序 cout 升序: ; sort(arr.begin(), arr.end(), Ascending()); for (int x : arr) cout x ; cout endl; cout 降序: ; sort(arr.begin(), arr.end(), Descending()); for (int x : arr) cout x ; cout endl; cout 按绝对值: ; sort(arr.begin(), arr.end(), ByAbs()); for (int x : arr) cout x ; cout endl; return 0; }二、STL内置仿函数C标准库提供了常用的仿函数位于functional头文件中。分类仿函数功能算术运算plusTx yminusTx - ymultipliesTx * ydividesTx / ymodulusTx % ynegateT-x比较运算equal_toTx ynot_equal_toTx ! ygreaterTx ylessTx ygreater_equalTx yless_equalTx y逻辑运算logical_andTx ylogical_orTx || ylogical_notT!x#include iostream #include vector #include algorithm #include functional using namespace std; int main() { vectorint arr {5, 2, 8, 1, 9, 3}; // 降序排序使用greater仿函数 sort(arr.begin(), arr.end(), greaterint()); cout 降序: ; for (int x : arr) cout x ; cout endl; // 升序排序使用less仿函数 sort(arr.begin(), arr.end(), lessint()); cout 升序: ; for (int x : arr) cout x ; cout endl; // 计算累加使用plus仿函数 int sum accumulate(arr.begin(), arr.end(), 0, plusint()); cout 总和: sum endl; // 计算乘积使用multiplies仿函数 int product accumulate(arr.begin(), arr.end(), 1, multipliesint()); cout 乘积: product endl; return 0; }三、在set/map中使用自定义仿函数#include iostream #include set #include string using namespace std; // 不区分大小写的比较仿函数 struct CaseInsensitiveCompare { bool operator()(const string a, const string b) const { size_t i 0; while (i a.size() i b.size()) { char ca tolower(a[i]); char cb tolower(b[i]); if (ca ! cb) return ca cb; i; } return a.size() b.size(); } }; int main() { // 使用自定义仿函数作为set的比较器 setstring, CaseInsensitiveCompare names; names.insert(Apple); names.insert(apple); // 被认为是重复的 names.insert(BANANA); names.insert(Banana); // 被认为是重复的 cout 不区分大小写的set: ; for (const auto name : names) { cout name ; } cout endl; // 输出Apple BANANA只保留第一个 return 0; }第四部分仿函数 vs Lambda 表达式C11引入了Lambda表达式可以非常简洁地创建匿名函数对象。Lambda的底层实现就是一个仿函数。#include iostream #include vector #include algorithm using namespace std; // 仿函数版本 struct GreaterThan { int threshold; GreaterThan(int t) : threshold(t) {} bool operator()(int x) const { return x threshold; } }; int main() { vectorint arr {1, 5, 2, 8, 3, 9, 4}; int threshold 5; // 仿函数版本 int count1 count_if(arr.begin(), arr.end(), GreaterThan(threshold)); // Lambda表达式版本完全等价 int count2 count_if(arr.begin(), arr.end(), [threshold](int x) { return x threshold; }); cout 大于 threshold 的元素个数: count1 endl; return 0; }仿函数 vs Lambda 对比特性仿函数Lambda代码量较多简洁可读性较好有名字简单逻辑好复杂逻辑差复用性可多处重用通常单次使用性能相同Lambda是语法糖相同捕获状态成员变量捕获列表类型有具体名称匿名类型适用场景复杂逻辑、需要重用简单逻辑、一次性使用选择建议简单逻辑一行代码→ Lambda复杂逻辑多行→ 仿函数需要在多处使用 → 仿函数需要携带大量状态 → 仿函数只在当前函数内使用一次 → Lambda第五部分高级应用一、累加器仿函数#include iostream #include vector #include numeric using namespace std; // 动态累加器仿函数 templatetypename T class Accumulator { private: T sum 0; int count 0; public: T operator()(T value) { sum value; count; return sum; } T getSum() const { return sum; } int getCount() const { return count; } T getAverage() const { return count ? sum / count : 0; } void reset() { sum 0; count 0; } }; int main() { Accumulatorint acc; vectorint nums {10, 20, 30, 40, 50}; for (int x : nums) { cout 累加和: acc(x) endl; } cout 总次数: acc.getCount() endl; cout 平均值: acc.getAverage() endl; return 0; }二、函数适配器预C11在C11之前可以使用bind1st、bind2nd适配仿函数。#include iostream #include vector #include algorithm #include functional using namespace std; int main() { vectorint arr {10, 20, 30, 40, 50, 60}; // C98/03 风格将lessint适配为大于30的比较 // 找出第一个大于30的元素 // vectorint::iterator it find_if(arr.begin(), arr.end(), // bind2nd(greaterint(), 30)); // C11后直接使用lambda更简洁 auto it find_if(arr.begin(), arr.end(), [](int x) { return x 30; }); if (it ! arr.end()) { cout 第一个大于30的元素: *it endl; } return 0; }第六部分完整示例——排序与统计程序#include iostream #include vector #include algorithm #include string #include iomanip using namespace std; // 学生结构体 struct Student { string name; int score; int id; }; // 按成绩降序排序 struct ByScoreDesc { bool operator()(const Student a, const Student b) const { return a.score b.score; } }; // 按ID升序排序 struct ByIDAsc { bool operator()(const Student a, const Student b) const { return a.id b.id; } }; // 按姓名排序 struct ByName { bool operator()(const Student a, const Student b) const { return a.name b.name; } }; // 统计成绩分区间的学生数量 struct ScoreStat { int excellent 0; // 90 int good 0; // 80-89 int pass 0; // 60-79 int fail 0; // 60 void operator()(const Student s) { if (s.score 90) excellent; else if (s.score 80) good; else if (s.score 60) pass; else fail; } void print() const { cout 优秀(90): excellent 人 endl; cout 良好(80-89): good 人 endl; cout 及格(60-79): pass 人 endl; cout 不及格(60): fail 人 endl; } }; // 打印学生列表 void printStudents(const vectorStudent students, const string title) { cout \n title endl; cout left setw(10) ID setw(10) 姓名 成绩 endl; cout ------------------- endl; for (const auto s : students) { cout left setw(10) s.id setw(10) s.name s.score endl; } } int main() { vectorStudent students { {1004, 张三, 85}, {1002, 李四, 92}, {1005, 王五, 67}, {1001, 赵六, 78}, {1003, 钱七, 55}, {1006, 孙八, 95}, {1007, 周九, 88} }; // 按成绩降序 printStudents(students, 原始数据); sort(students.begin(), students.end(), ByScoreDesc()); printStudents(students, 按成绩降序); sort(students.begin(), students.end(), ByIDAsc()); printStudents(students, 按ID升序); // 统计成绩分布 ScoreStat stat for_each(students.begin(), students.end(), ScoreStat()); cout \n 成绩统计 endl; stat.print(); return 0; }总结一、仿函数核心要点概念说明本质重载operator()的类对象调用方式obj(args)等价于obj.operator()(args)优势可携带状态、性能好、类型安全适用STL算法参数、复杂逻辑封装二、常用STL仿函数分类仿函数功能比较greaterT、lessT大于、小于算术plusT、minusT加、减逻辑logical_andT、logical_orT与、或三、使用建议// 简单逻辑 → Lambda sort(v.begin(), v.end(), [](int a, int b) { return a b; }); // 复杂逻辑 → 仿函数 struct ComplexCompare { bool operator()(const Data a, const Data b) const { // 复杂比较逻辑... } }; // 需要携带状态 → 仿函数 struct Counter { int count 0; void operator()() { count; } }; // 需要复用 → 仿函数 MyFunctor func; // 多处使用仿函数是C中一个重要的设计模式它在STL中扮演着关键角色。虽然C11的Lambda表达式在很多场景下可以替代仿函数但理解仿函数的原理仍然重要——因为Lambda的底层实现就是仿函数。学习建议理解operator()重载的基本语法掌握使用仿函数作为STL算法参数熟悉常用的STL内置仿函数了解仿函数与Lambda的等价关系和使用场景

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2579546.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…

wordpress后台更新后 前端没变化的解决方法

使用siteground主机的wordpress网站,会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后,网站没有变化的情况。 不熟悉siteground主机的新手,遇到这个问题,就很抓狂,明明是哪都没操作错误&#x…

网络编程(Modbus进阶)

思维导图 Modbus RTU(先学一点理论) 概念 Modbus RTU 是工业自动化领域 最广泛应用的串行通信协议,由 Modicon 公司(现施耐德电气)于 1979 年推出。它以 高效率、强健性、易实现的特点成为工业控制系统的通信标准。 包…

UE5 学习系列(二)用户操作界面及介绍

这篇博客是 UE5 学习系列博客的第二篇,在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下: 【Note】:如果你已经完成安装等操作,可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作,重…

IDEA运行Tomcat出现乱码问题解决汇总

最近正值期末周,有很多同学在写期末Java web作业时,运行tomcat出现乱码问题,经过多次解决与研究,我做了如下整理: 原因: IDEA本身编码与tomcat的编码与Windows编码不同导致,Windows 系统控制台…

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…

XML Group端口详解

在XML数据映射过程中&#xff0c;经常需要对数据进行分组聚合操作。例如&#xff0c;当处理包含多个物料明细的XML文件时&#xff0c;可能需要将相同物料号的明细归为一组&#xff0c;或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码&#xff0c;增加了开…

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…

(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)

题目&#xff1a;3442. 奇偶频次间的最大差值 I 思路 &#xff1a;哈希&#xff0c;时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况&#xff0c;哈希表这里用数组即可实现。 C版本&#xff1a; class Solution { public:int maxDifference(string s) {int a[26]…

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…

【Axure高保真原型】引导弹窗

今天和大家中分享引导弹窗的原型模板&#xff0c;载入页面后&#xff0c;会显示引导弹窗&#xff0c;适用于引导用户使用页面&#xff0c;点击完成后&#xff0c;会显示下一个引导弹窗&#xff0c;直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…

接口测试中缓存处理策略

在接口测试中&#xff0c;缓存处理策略是一个关键环节&#xff0c;直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性&#xff0c;避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明&#xff1a; 一、缓存处理的核…

龙虎榜——20250610

上证指数放量收阴线&#xff0c;个股多数下跌&#xff0c;盘中受消息影响大幅波动。 深证指数放量收阴线形成顶分型&#xff0c;指数短线有调整的需求&#xff0c;大概需要一两天。 2025年6月10日龙虎榜行业方向分析 1. 金融科技 代表标的&#xff1a;御银股份、雄帝科技 驱动…

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …

华为云AI开发平台ModelArts

华为云ModelArts&#xff1a;重塑AI开发流程的“智能引擎”与“创新加速器”&#xff01; 在人工智能浪潮席卷全球的2025年&#xff0c;企业拥抱AI的意愿空前高涨&#xff0c;但技术门槛高、流程复杂、资源投入巨大的现实&#xff0c;却让许多创新构想止步于实验室。数据科学家…

深度学习在微纳光子学中的应用

深度学习在微纳光子学中的主要应用方向 深度学习与微纳光子学的结合主要集中在以下几个方向&#xff1a; 逆向设计 通过神经网络快速预测微纳结构的光学响应&#xff0c;替代传统耗时的数值模拟方法。例如设计超表面、光子晶体等结构。 特征提取与优化 从复杂的光学数据中自…