在成员函数中使用STL的find_if函数
2012-10-18 21:17
387 查看
STL的find_if函数功能很强大,可以使用输入的函数替代等于操作符执行查找功能(这个网上有很多资料,我这里就不多说了)。
比如查找一个数组中的奇数,可以用如下代码完成(具体参考这里:http://www.cplusplus.com/reference/algorithm/find_if/):
运行结果:
如果把上述代码加入到类里面,写成类的成员函数,又是什么效果呢?
比如如下类代码:
View Code
会出现类似下面的错误:
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
好,就这些了,希望对你有帮助。
比如查找一个数组中的奇数,可以用如下代码完成(具体参考这里: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
如果把上述代码加入到类里面,写成类的成员函数,又是什么效果呢?
比如如下类代码:
View Code
#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
好,就这些了,希望对你有帮助。
相关文章推荐
- 在成员函数中使用STL的find_if函数
- C++在成员函数中使用STL的find_if函数实例
- 成员函数中使用STL的find_if函数
- 如何在 Visual C++ 中使用 STL 队列类的该成员函数
- STL使用list的成员函数push_back和push_front插入一个元素到list中
- STL(1)——查找函数find的使用
- 关于在STL容器list中使用find_if 函数
- Stl中使类成员函数成为谓词,mem_fun 和mem_fun_ref的使用
- 使用成员函数管理map STL
- (使用STL自带的排序函数进行排序7.3.6)POJ 2945 Find the Clones拷贝相同次数的文本出现了多少次()
- Effective STL: Item 44:优先使用与泛型算法同名的成员函数
- STL中的for_each调用类成员函数,mem_fun, mem_fun_ref用法
- C#中使用托管C++类,委托调用,以供托管C++类的成员函数回调的实现方式
- STL中仿函数(functors)、类成员和mem_fun的使用
- STL中copy函数使用的例子
- (原創) 如何使用find_first_of() algorithm? (C/C++) (STL)
- stl 中list 或者vector正确使用find查找类对象
- C++中各种数据成员及成员函数的定义及使用
- 类的静态成员变量和静态成员函数的使用方法一
- 关于类成员函数在模板中的使用