在成员函数中使用STL的find_if函数
STL的find_if函数功能很强大,可以使用输入的函数替代等于操作符执行查找功能(这个网上有很多资料,我这里就不多说了)。
比如查找一个数组中的奇数,可以用如下代码完成(具体参考这里:http://www.cplusplus.com/reference/algorithm/find_if/):
#include <iostream> #include <algorithm> #include <vector> using namespace std; bool IsOdd (int i) { return ((i%2)==1); } int main () { vector<int> myvector; vector<int>::iterator it; myvector.push_back(10); myvector.push_back(25); myvector.push_back(40); myvector.push_back(55); it = find_if (myvector.begin(), myvector.end(), IsOdd); cout << "The first odd value is " << *it << endl; return 0; }
运行结果:
The first odd value is 25
如果把上述代码加入到类里面,写成类的成员函数,又是什么效果呢?
比如如下类代码:

#include <iostream> #include <algorithm> #include <vector> using namespace std; class CTest { public: bool IsOdd (int i) { return ((i%2)==1); } int test () { vector<int> myvector; vector<int>::iterator it; myvector.push_back(10); myvector.push_back(25); myvector.push_back(40); myvector.push_back(55); it = find_if (myvector.begin(), myvector.end(), IsOdd); cout << "The first odd value is " << *it << endl; return 0; } }; int main() { CTest t1; t1.test(); return 0; }
会出现类似下面的错误:
error C3867: 'CTest::IsOdd': function call missing argument list; use '&CTest::IsOdd' to create a pointer to member
今天我就遇到了这个问题,这里把解决方案贴出来,仅供参考:
it = find_if (myvector.begin(), myvector.end(), IsOdd);
改为:
it = find_if(myvector.begin(), myvector.end(),std::bind1st(std::mem_fun(&CTest::IsOdd),this));
用bind1st函数和mem_fun函数加上this指针搞定的。
完整代码参考这里:https://gist.github.com/3910390
好,就这些了,希望对你有帮助。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)