头文件:<functional>
看这篇文章前,请先看 ptr_fun的使用 和 STL 中 mem_fun 和 mem_fun_ref 的用法
bind1st和bind2nd函数把一个二元函数对象绑定成为一个一元函数对象。 但是由于二元函数对象接受两个参数,在绑定成为一元函数对象时需要将原来两个参数中的一个绑定下来。 也即通过绑定二元函数对象的一个参数使之成为一元函数对象的。 bind1st是绑定第一个参数,bind2nd则是绑定第二个参数。
下面代码来自 http://blog.csdn.net/huang_xw/article/details/8223617
void test_func_bind() { std::vector<int> v1; std::vector<int>::iterator Iter; int i; for (i = 0; i <= 5; i++) { v1.push_back(5 * i); } std::cout << "The vector v1 = ( "; std::copy(v1.cbegin(), v1.cend(), std::ostream_iterator<int>(std::cout, " ")); std::cout << ")" << std::endl; // Count the number of integers > 10 in the vector std::vector<int>::iterator::difference_type result1a; result1a = count_if(v1.begin(), v1.end(), bind1st(std::less<int>(), 10)); std::cout << "The number of elements in v1 greater than 10 is: " << result1a << "." << std::endl; // Count the number of integers < 10 in the vector std::vector<int>::iterator::difference_type result2; result2 = count_if(v1.begin(), v1.end(), bind2nd(std::less<int>(), 10)); std::cout << "The number of elements in v1 less than 10 is: " << result2 << "." << std::endl; }
也是可以的,对于bind2nd,因为只有一个参数位置,因此它只能绑定这唯一的参数,对于bind1st是不可以的。为什么bind1st不可以,个人理解,只是个人理解,理解不对的话请改正,大家知道类成员函数都有一个隐藏的this,或许这个this充当了第一参数。
复制了一篇不错的代码,原文链接:http://classfoo.com/ccby/article/2CGheO
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <functional> #include <sstream> namespace ClassFoo { using namespace std; class Person { private: std::string name; static int n; public: Person() { std::stringstream ss; std::string snum; ss << n++; ss >> snum; name = "foo" + snum; } void print() const { std::cout << name << std::endl; } void printWithPrefix(std::string prefix) const { std::cout << prefix << name << std::endl; } }; int Person::n = 0; void foo(const std::vector<Person>& coll) { // 对每个元素对象调用成员函数 print() for_each(coll.begin(), coll.end(), mem_fun_ref(&Person::print)); // 对每个元素对象调用成员函数 printWithPrefix() // - "person: " 作为参数传递给成员函数 for_each(coll.begin(), coll.end(), bind2nd(mem_fun_ref(&Person::printWithPrefix), "person: ")); } void ptrfoo(const std::vector<Person*>& coll) { // 对每个指针指向的元素对象调用成员函数 print() for_each(coll.begin(), coll.end(), mem_fun(&Person::print)); // 对每个指针指向的元素对象调用成员函数 printWithPrefix() // - "person: " 作为参数传递给成员函数 for_each(coll.begin(), coll.end(), bind2nd(mem_fun(&Person::printWithPrefix), "person: ")); } void ForEach_2() { std::cout << "当向量的元素是对象时:" << std::endl; std::vector<ClassFoo::Person> coll(5); ClassFoo::foo(coll); std::cout << "当向量的元素是指向对象的指针时:" << std::endl; std::vector<ClassFoo::Person*> coll2; coll2.push_back(new ClassFoo::Person); coll2.push_back(new ClassFoo::Person); coll2.push_back(new ClassFoo::Person); coll2.push_back(new ClassFoo::Person); coll2.push_back(new ClassFoo::Person); ptrfoo(coll2); } } int main() { ClassFoo::ForEach_2(); return 0; }