2013-05-20 41 views
0

我想了解std :: bind如何工作。我寫了以下內容:在C++中使用std :: bind與二進制操作函數

#include <iostream> 
#include <algorithm> 
#include <functional> 


using namespace std::placeholders; 

int fun2(int i,int j) 
{ 
    return i+j; 
} 


int fun(int i) 
{ 
    return i; 
} 

int main() 
{ 
std::vector<int> v9={1,2,3,4,5,6,6,7}; 
std::transform(v9.begin(),v9.end(),v9.begin(),[](int i){return i;}); //works 
std::transform(v9.begin(),v9.end(),v9.begin(),fun); //works 
std::transform(v9.begin(),v9.end(),v9.begin(),std::bind(fun,_1)); //works 
std::transform(v9.begin(),v9.end(),v9.begin(),std::bind(fun2,_1,_2)); //does not work 
} 

std :: transform還接受二進制操作函數。所以我試圖寫fun2並使用std :: bind(main的最後一行),但它不起作用。有人可以給我任何例子如何使用std :: bind佔位符(2,3或更多)?

+0

'std :: transform'只傳遞一個參數。你的意思是做'std :: bind(fun2,_1,5)'嗎? – chris

+3

除了當它通過兩個:[(2)](http://en.cppreference.com/w/cpp/algorithm/transform :) :) – jrok

+2

如果你不'使用'std :: bind'確實沒有意義, t綁定任何參數。 –

回答

4

採用二元函子的std::transform的重載需要四個迭代器,而不是三個,因爲它在兩個輸入範圍上運行,而不是一個。例如:

#include <iostream> 
#include <algorithm> 
#include <functional> 
#include <iterator> 

int fun2(int i,int j) 
{ 
    return i+j; 
} 

int main() 
{ 
    using namespace std::placeholders; 
    std::vector<int> v1={1,2,3,4,5,6,6,7}; 
    std::vector<int> v2; 
    std::transform(v1.begin(), v1.end(), v1.begin(), 
       std::back_inserter(v2), std::bind(fun2,_1,_2)); 
    for (const auto& i : v2) 
    std::cout << i << " "; 
    std::cout << std::endl; 
} 

當然,在現實生活中,你就不會在這裏使用std::bind

+0

你說得對,我的錯。 'std :: transform(v9.begin(),v9.end(),v9.begin(),v9.end(),std :: bind(fun2,_1,_2));' –

+0

@AvraamMavridis:你確定該代碼給你同樣的錯誤?什麼是完整的錯誤? (如果Visual Studio,完整的錯誤在「輸出」窗口中,而不是「錯誤」窗口) –

+0

@MooingDuck代碼(在註釋中)不會給出任何錯誤,它會進行編譯。 –