c++ functor使用示例

    xiaoxiao2023-10-05  143

    // // 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; }
    最新回复(0)