std :: for_each和functors - operator()有哪些签名?

时间:2013-12-10 01:06:19

标签: c++ foreach functor

我想使用std::for_each调用来循环访问某些值,并调用一个仿函数将值映射到字符串,并将该值返回到for_each,如下所示:

#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应用,正如我正在尝试的那样?除operator()的隐含范围变量外,是否可以将其他参数传递给for_each

如果operator()有可能有返回值,我该如何编写myfunctor-to-string转换方法?

我从未见过void operator()(SingleArgument)

以外的任何其他例子

1 个答案:

答案 0 :(得分:3)

首先,您必须将您的仿函数作为第三个参数传递给std::for_each。您正在传递函数调用blah.append(t)的结果。此外,函数是for_each期间应该全部工作的事情,因此您必须将调用转移到appendoperator()内部1}}。最简单的方法:只需将您的字符串作为参考传递。

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;
}