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