zoukankan      html  css  js  c++  java
  • 在成员函数中使用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

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

  • E-Mail : Mike_Zhang@live.com
  • 转载请注明出处,谢谢!
查看全文
  • 相关阅读:
    ccnet 配置真折腾
    幻灯片效果代码(asp版本)
    Microsoft Office 服务器系统要求
    取数据库N到M的记录
    [心得]关于iframe页面滚动条。
    和我一起学Windows Workflow Foundation(2)让WF通过参数接收数据 [转]
    新闻图片效果
    AJAX
    和我一起学Windows Workflow Foundation(1)创建和调试一个WF实例 [转]
    关闭父窗口,打开新窗口
  • 原文地址:https://www.cnblogs.com/MikeZhang/p/STL_find_if_inMemberFunction.html
  • Copyright © 2011-2022 走看看