1. 程式人生 > 其它 >C++的std::bind1st和std::bind2nd

C++的std::bind1st和std::bind2nd

技術標籤:C++

一、介紹

標頭檔案:fuctional

std::bind1st和std::bind2nd函式用於將一個二元運算元轉換成一元運算元。bind的意思是“繫結”,1st代表first,2nd代表second,它們的宣告如下:

template< class F, class T >
std::binder1st<F> bind1st( const F& f, const T& x );

template< class F, class T >
std::binder2nd<F> bind2nd( const F& f, const T& x );

將給定的引數x繫結到二元函式物件F的第一個或第二個形參。也就是說,將x儲存在該包裝器中,如果呼叫該包裝器,則將x作為F的第一個或第二個形參傳遞。

Binds a given argument x to a first or second parameter of the given binary function object f. That is, stores x within the resulting wrapper, which, if called, passes x as the first or the second parameter of f.

bind1st相當於作這樣的操作:x Operation value;

bind2nd相當於作這樣的操作:value Operation x;

二、用法

#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    vector<int> coll = { 1,2,3,5,15,16,18 };

    // 查詢元素值大於10的元素的個數
    // 也就是使得10 < elem成立的元素個數 
    int res = count_if(coll.begin(), coll.end(), bind1st(less<int>(), 10));
    cout << res << endl;

    // 查詢元素值小於10的元素的個數
    // 也就是使得elem < 10成立的元素個數 
    res = count_if(coll.begin(), coll.end(), bind2nd(less<int>(), 10));
    cout << res << endl;

    return 0;

}

對於上面的程式碼,less<int>()其實是一個仿函式,如果沒有std::bind1st和std::bind2nd,那麼我們可以這樣使用less<int>(),程式碼如下:

less<int> functor = less<int>();
bool bRet = functor(10, 20); // 返回true

看到了麼?less<int>()這個仿函式物件是需要兩個引數的,比如10<20進行比較,那麼10叫做left引數,20叫做right引數。

  • 當使用std::bind1st的時候,就表示綁定了left引數,也就是left引數不變了,而right引數就是對應容器中的element;
  • 當使用std::bind2nd的時候,就表示綁定了right引數,也就是right引數不變了,而left引數就是對應容器中的element

參考:

https://en.cppreference.com/w/cpp/utility/functional/bind12

https://blog.csdn.net/u013654125/article/details/100140328