• 仿函数


    ceres里面用到仿函数,故单独测试一下用法

    #include <iostream>
    #include <string>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    class LessThenLenFunctor{
    public:
        bool operator()(const string& str){
            return str.length() < len;
        }
    
        //构造函数
        LessThenLenFunctor(int l):len(l){};
    
    private:
        int len;
    };
    
    int main()
    {
        vector<string> sVec{"aegew", "ssftat", "12"};
        int cnt = count_if(sVec.begin(), sVec.end(),LessThenLenFunctor(6));
        cout << cnt << endl;
    }

    可以让LessThenLenFunctor类作为一个函数被使用,其中类的成员变量作为这个函数的参数,具有较大的灵活性。

    参考:https://blog.csdn.net/codedoctor/article/details/79654690

    另外,也可以通过lamda(匿名函数)来实现相同的功能

    #include <iostream>
    #include <string>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    class LessThenLenFunctor{
    public:
        bool operator()(const string& str){
            return str.length() < len;
        }
    
        //构造函数
        LessThenLenFunctor(int l):len(l){};
    
    private:
        int len;
    };
    
    int main()
    {
        vector<string> sVec{"aegew", "ssftat", "12"};
        int x = 6;
       // int cnt = count_if(sVec.begin(), sVec.end(),LessThenLenFunctor(6));
       int cnt = count_if(sVec.begin(), sVec.end(), [x](string str){return str.length() < x;});
        cout << cnt << endl;
    }

     关于lamda的使用,https://blog.csdn.net/bajianxiaofendui/article/details/86583612,这里讲的比较清楚,自己也可以验证一下。

  • 相关阅读:
    Rational Rose 2003 逆向工程转换C++ / VC++ 6.0源代码成UML类图
    用VC实现特定编辑框上对回车键响应
    22.职责链模式
    21.策略模式
    20.状态模式
    19.解释器模式
    18.备忘录模式
    17.中介者模式
    16.观察者模式
    15.迭代器模式
  • 原文地址:https://www.cnblogs.com/havain/p/15506892.html
Copyright © 2020-2023  润新知