- // bind1st和bind2nd函数把一个二元函数对象绑定成为一个一元函数对象。
- // 但是由于二元函数对象接受两个参数,在绑定成为一元函数对象时需要将原来两个参数中的一个绑定下来。
- // 也即通过绑定二元函数对象的一个参数使之成为一元函数对象的。
- // bind1st是绑定第一个参数,bind2nd则是绑定第二个参数。
- // 我个人喜欢用bind2nd,这样子代码读起来更顺。
- class greaterthan5: std::unary_function<int, bool>
- {
- public:
- result_type operator()(argument_type i)
- {
- return (result_type)(i > 5);
- }
- };
- 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;
- // Compare: counting the number of integers > 5 in the vector
- // with a user defined function object
- std::vector<int>::iterator::difference_type result1b;
- result1b = count_if(v1.begin(), v1.end(), greaterthan5());
- std::cout << "The number of elements in v1 greater than 5 is: "
- << result1b << "." << 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;
- }
bind1st与bind2nd函数解析
最新推荐文章于 2024-03-15 13:19:09 发布