仿函数

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,这里讲的比较清楚,自己也可以验证一下。

原文地址:https://www.cnblogs.com/havain/p/15506892.html