2011-07-28 32 views
5
vector<int> vwInts; 
vector<int> vwIntsB; 

for(int i=0; i<10; i++) 
    vwInts.push_back(i); 

transform(vwInts.begin(), vwInts.end(), inserter(vwIntsB, vwIntsB.begin()), 
     bind1st(plus<int>(), 5)); // method one 

transform(vwInts.begin(), vwInts.end(), inserter(vwIntsB, vwIntsB.begin()), 
     bind2nd(plus<int>(), 5)); // method two 

我知道bind1st和bind2nd之間的用法區別,方法一和方法二都爲我提供了預期的結果。使用bind1st或bind2nd?

在這種情況下(即轉換的用法)是否真的沒有太大的區別,以便我可以使用bind1st或bind2nd?

因爲,我迄今爲止看到的所有例子總是使用方法二。我想知道在上述情況下bind1st和bind2nd是否相同。

+0

是相同的,我會建議你尋找到的boost ::綁定如果你還沒有。它比bind1st和bind2nd更靈活,更強大。 –

回答

4

bind1st綁定函數的第一個參數,而bind2nd綁定第二個參數。由於這兩種參數類型在這種情況下是相同的,並且operator+是對稱的,所以它們沒有區別。

3

在這種情況下,他們會分別翻譯爲5 + a和a + 5,編譯完全一樣。

6

bind1st綁定plus<int>()仿函數的第一個參數,bind2nd綁定第二個參數。在plus<int>的情況下,它沒有任何區別,因爲10+2020+10是相同的。

但是,如果你這樣做與minus<int>,它會產生差異,因爲10-2020-10是不一樣的。試試這樣做。

插圖:

int main() { 
    auto p1 = bind1st(plus<int>(),10); 
    auto p2 = bind2nd(plus<int>(),10); 
    cout << p1(20) << endl; 
    cout << p2(20) << endl; 

    auto m1 = bind1st(minus<int>(),10); 
    auto m2 = bind2nd(minus<int>(),10); 
    cout << m1(20) << endl; 
    cout << m2(20) << endl; 
    return 0; 
} 

輸出:

30 
30 
-10 
10 

演示:http://ideone.com/IfSdt

0

對於你的具體情況

bind1st() 

bind2nd() 

相同

這樣是因爲,plus()二元函數operator看起來像下面

plus(arg1, arg2) 

所以,當你使用bind1st(plus<int>(), 5)調用加上看上去就像下

plus(5, vwInts) 

所以,上面會增加每一個元素具有值的向量5

而當您使用bind2nd(plus<int>(), 5)呼叫加上wou LD外表如下

plus(vwInts, 5) 

所以,以上將向量的每個元素添加用一個值5

因此都在你的情況