溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

C++ STL bind1st bind2nd bind 的使用方法

發(fā)布時(shí)間:2021-07-19 10:48:23 來(lái)源:億速云 閱讀:125 作者:chen 欄目:互聯(lián)網(wǎng)科技

本篇內(nèi)容主要講解“C++ STL bind1st bind2nd bind 的使用方法”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“C++ STL bind1st bind2nd bind 的使用方法”吧!

說(shuō)明

bind1st() 和 bind2nd(),在 C++11 里已經(jīng) deprecated 了,建議使用新標(biāo)準(zhǔn)的 bind()
下面先說(shuō)明bind1st() 和 bind2nd()的用法,然后在說(shuō)明bind()的用法。

頭文件

#include <functional>

作用

bind1st()bind2nd()都是把二元函數(shù)轉(zhuǎn)化為一元函數(shù),方法是綁定其中一個(gè)參數(shù)。
bind1st()是綁定第一個(gè)參數(shù)。
bind2nd()是綁定第二個(gè)參數(shù)。

例子

#include <iostream>#include <algorithm> #include <functional> using namespace std; int main() { int numbers[] = { 10,20,30,40,50,10 }; int cx; cx = count_if(numbers, numbers + 6, bind2nd(less<int>(), 40)); cout << "There are " << cx << " elements that are less than 40.\n"; cx = count_if(numbers, numbers + 6, bind1st(less<int>(), 40)); cout << "There are " << cx << " elements that are not less than 40.\n"; system("pause"); return 0; }
There are 4 elements that are less than 40.There are 1 elements that are not less than 40.

分析
less()是一個(gè)二元函數(shù),less(a, b)表示判斷a<b是否成立。

所以bind2nd(less<int>(), 40)相當(dāng)于x<40是否成立,用于判定那些小于40的元素。

bind1st(less<int>(), 40)相當(dāng)于40<x是否成立,用于判定那些大于40的元素。

bind()

bind1st() 和 bind2nd(),在 C++11 里已經(jīng) deprecated 了.bind()可以替代他們,且用法更靈活更方便。

上面的例子可以寫(xiě)成下面的形式:

#include <iostream>#include <algorithm> #include <functional> using namespace std; int main() { int numbers[] = { 10,20,30,40,50,10 }; int cx; cx = count_if(numbers, numbers + 6, bind(less<int>(), std::placeholders::_1, 40)); cout << "There are " << cx << " elements that are less than 40.\n"; cx = count_if(numbers, numbers + 6, bind(less<int>(), 40, std::placeholders::_1)); cout << "There are " << cx << " elements that are not less than 40.\n"; system("pause"); return 0; }

std::placeholders::_1 是占位符,標(biāo)定這個(gè)是要傳入的參數(shù)。
所以bind()不僅可以用于二元函數(shù),還可以用于多元函數(shù),可以綁定多元函數(shù)中的多個(gè)參數(shù),不想綁定的參數(shù)使用占位符表示。
此用法更靈活,更直觀,更便捷。

到此,相信大家對(duì)“C++ STL bind1st bind2nd bind 的使用方法”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢(xún),關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI