Question

I want to use a std::for_each call to loop through some values and invoke a functor to map the value to a string, and return that value to the for_each, like so:

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

It doesn't compile because it can't convert from a myfunctor to a string. But even if it did, is it legal to return something from operator(), to be applied by the for_each as I'm trying to do? Is it possible to pass other parameters to operator() besides the implied range variable of the for_each?

If it is possible for operator() to have a return value, how would I write a myfunctor-to-string conversion method?

I;ve just never seen examples of anything other than void operator()(SingleArgument)

Was it helpful?

Solution

First, you have to pass your functor to std::for_each as a third argument. You are passing the result of the function call blah.append(t). Also, the functor is the thing that is supposed to do all the work during the for_each, so you'll have to shift the call to append to inside the operator(). Easiest way: just pass your string as a reference.

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top