【STL】bind1st與bind2nd函式解析
阿新 • • 發佈:2019-02-17
// 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; }