2013-12-10 62 views
1

我想通過一些值使用std::for_each調用循環並調用仿函數映射值的字符串,並將該值返回for_each,像這樣:std :: for_each和functors - operator()有哪些簽名?

#include <iostream> 
#include <map> 
#include <string> 
using std::string; 
using std::map; 
using std::cout; 
using std::endl; 

struct myfunctor 
{ 
    myfunctor(map<int, string>& x) : mymap(x) { 
     cout << "Inside myfunctor ctor" << endl; 
    }; 

    map<int, string>& mymap; 

    string operator()(int mapthis) 
    { 
     cout << "Inside myfunctor operator(" << mapthis << ")" << endl; 
     return mymap[mapthis]; 
    } 
}; 

int main() 
{ 
    map<int, string> codes { {1, "abel"}, {2, "baker"}, {3, "charlie"} }; 

    cout << "Main() - construct myfunctor" << endl; 
    myfunctor t(codes); 

    int arr[] = {1, 2, 3}; 

    string blah; 
    cout << "Main() - begin for_each" << endl; 
    std::for_each(arr, arr+2, blah.append(t)); 
    cout << blah << endl; 
} 

它不會編譯,因爲它無法從myfunctor轉換爲string。但即使這樣做,從operator()返回一些東西是否合法,for_each正如我試圖做的那樣適用?除了隱含的範圍變量for_each之外,是否可以將其他參數傳遞給operator()

如果operator()可能有返回值,我該如何編寫myfunctor-to-string轉換方法?

我,已經比void operator()(SingleArgument)

回答

3

第一其它任何只是從來沒有看到的例子,你有你的仿函數傳遞給std::for_each作爲第三個參數。您正在傳遞函數調用blah.append(t)的結果。此外,函數是全部for_each期間的工作,因此您必須將呼叫轉移到append以內operator()。最簡單的方法:只是傳遞你的字符串作爲參考。

struct myfunctor 
{ 
    myfunctor(string& toAppend, map<int, string>& x) : appendage(toAppend), mymap(x) { 
     cout << "Inside myfunctor ctor" << endl; 
    }; 

    map<int, string>& mymap; 
    string& appendage; 

    void operator()(int mapthis) 
    { 
     cout << "Inside myfunctor operator(" << mapthis << ")" << endl; 
     appendage.append(mymap[mapthis]); 
      //std::for_each will not use a return value of this function for anything 
    } 
}; 

void main2() 
{ 
    map<int, string> codes { {1, "abel"}, { 2, "baker" }, { 3, "charlie" } }; 

    cout << "Main() - construct myfunctor" << endl; 


    int arr[] = { 1, 2, 3 }; 

    string blah; 
    myfunctor t(blah, codes); //Pass in blah so the functor can append to it. 
    cout << "Main() - begin for_each" << endl; 
    std::for_each(arr, arr + 3, t); //arr+3 to loop over all 3 elems of arr 
    cout << blah << endl; 
} 
+0

正是我想要的。我的理解是否正確:這裏的想法是,for_each的第三個參數是一個* object *,而不是一個真正的函數調用? – Chap

+1

@chap它是一個定義了'operator()'的對象,並且'()'將由'for_each'和該範圍的元素重複調用。請注意,函數指針符合簽名是否匹配。 – Yakk

相關問題