本文实例讲述了C++在成员函数中使用STL的find_if函数的方法。分享给大家供大家参考。具体方法分析如下:
一般来说,STL的find_if函数功能很强大,可以使用输入的函数替代等于操作符执行查找功能(这个网上有很多资料,我这里就不多说了)。
比如查找一个数组中的奇数,可以用如下代码完成(具体参考这里:http://www.cplusplus.com/reference/algorithm/find_if/):
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#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;
}
|
运行结果:
?
1
|
The first odd value is 25
|
如果把上述代码加入到类里面,写成类的成员函数,又是什么效果呢?
比如如下类代码:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
#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指针搞定的。
完整实例代码点击此处本站下载。
希望本文所述对大家的C++程序设计有所帮助。
相关文章
猜你喜欢
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 25
-
2025-05-25 13
-
2025-05-27 62
-
2025-05-29 67
-
2025-05-27 42
热门评论