【STL】bind1st與bind2nd函數解析

來源:互聯網
上載者:User
// 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 vectorstd::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 objectstd::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 vectorstd::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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.