The cool thing about for_each is:
1) you can pass the function objects by reference
I don't see how that could work. I thought the function
object is always passed by value? I tried passing a function
object to a for_each loop once, where the function object was
collecting data about operations. But that didn't work,
because for_each used a *copy* of the object, rather than the
object itself.
I was writing a spelling-checker, just for programming
practice. The for_each loop looked something like:
Append FuncObj = Append(Dictionary);
for_each(Dicts.begin(), Dicts.end(), FuncObj);
("Dicts" is a list of file paths, and "Dictionary" is a list
of words.)
But the the counts of files and lines went into the unnamed
*copy* of FuncObj, not FuncObj itself.
2) you can apply side-effects on the function object
?
3) you can use the return value of the for_each() algorithm
Hmmm.... Interesting. Perhaps, then, something like the following
would work in my spelling checker (could be used to count files --
or lines -- appended to a list of strings):
Append FuncObjCopy =
for_each(Dicts.begin(), Dicts.end(), Append(Dictionary)
;
cout << "Files processed = " << FuncObjCopy.files << endl;
cout << "Lines processed = " << FuncObjCopy.lines << endl;
Not quite as nice as getting for_each to use the original function
object, but almost.