// //ptr_fun mem_fun_ref mem_fun //STL 算法函数有些要传入仿函数,例如remove_if()的第三个参数。 //许多情况下直接传入一个全局指针函数是不会报错的,有时则不然,例如:bind2nd(),这时需要使用ptr_fun; //当一个函数指针是类成员函数时,编译将不能通过。此时将使用到了mem_fun和mem_fun_ref。 //指针函数一般分三种,全局函数指针,对象成员函数指针根据对象是指针还是引用有分为两种。 //1)fun(); 使用 ptr_fun //2)a.fun(); 使用 mem_fun_ref //3)p->fun(); 使用 mem_fun //普通的C++程序多使用函数指针做参数传递,在STL中是使用仿函数做为参数传递标准,来提供函数指针的类似功能。 //以上三个函数就是将函数指针转化为彷函数的桥梁。 //ptr_fun() 仅仅支持一元参数和二元参数。太多或太少参数就自己定义彷函数吧。 //不过刚看看了STL源码,stl中的一些算法需要当参数传入的fun,对参数要求有限制,不能任意多个 //例如find_if(),需要的彷函数的参数只能是bool operator () (SMyData& aData) ; //SMyData代表了stl容器存储的数据类型。 // //bind1st bind2nd //bind1st和bind2nd函数用于把一个二元函数对象绑定成为一个一元函数对象 //bind1st是绑定第一个参数,bind2nd则是绑定第二个参数 void fun(int t, std::string separator) { std::cout << t << separator; } void fun2(std::string separator,int t) { std::cout << t << separator; } void bind_test() { // //test1: bind1st(ptr_fun(fun),1)(".../n");//相当于:fun(1,".../n"); bind2nd(ptr_fun(fun),(".../n"))(2); //相当于:fun(2,".../n"); //当bind1st(fun,1)这样使用时,编译不会出错,但是不会调研fun函数。 // //test2: //当与其他stl算法配合使用时,如下: std::vector<int> elements; elements.push_back(1); elements.push_back(2); elements.push_back(3); for_each(elements.begin(), elements.end(), std::bind2nd(ptr_fun(fun), "... /n")); //此时,bind2nd的第二个参数被绑定为printn中的第二个参数,第一个参数是当前迭代器所指的元素。 //bind1st同理。 for_each(elements.begin(), elements.end(), std::bind1st(ptr_fun(fun2), "... /n")); }