//
// Created by ashe on 2018-05-25.
//
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using std::vector;
using std::cout;
using std::endl;
using std::string;
bool length_is_less_than_5(string& s)
{
return s.length() < 5;
}
class Length_is_less_than
{
public:
Length_is_less_than(int length_in):length(length_in){
cout << "new Length_is_less_than instance" << endl;
};
bool operator() (const string& str) const {
cout << str << endl;
return str.length() < length;
}
private:
const int length;
};
void test_functor()
{
vector<string> vec_s = {"aa","BB"};
//使用std count_if進行vector string元素長度小於5的方法,如果普通函數,無法指定具體的長度
int res = count_if(vec_s.begin(),vec_s.end(),length_is_less_than_5);
//而使用functor,可以通過傳參的方式動態調整對比的長度
res = count_if(vec_s.begin(),vec_s.end(),Length_is_less_than(2));
cout << res << endl;
}
int main()
{
test_functor();
return 0;
}
c++ functor使用示例
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.