随笔 - 272  文章 - 0  评论 - 283  阅读 - 142万

在成员函数中使用STL的find_if函数

STLfind_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

如果把上述代码加入到类里面,写成类的成员函数,又是什么效果呢?

比如如下类代码:

复制代码
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

好,就这些了,希望对你有帮助。

posted on   Mike_Zhang  阅读(2157)  评论(5编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2012年10月 >
30 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 31 1 2 3
4 5 6 7 8 9 10

点击右上角即可分享
微信分享提示