I looked at the implementation of std::for_each and it became terribly interesting, why does this function return a function that we pass in the 3rd parameter? Is it used somehow?

    1 answer 1

    If you use a functional object as the third parameter, you can allocate this functional object with an internal state and accumulate in it some result that interests you. Then, upon completion of std::for_each , this result can be retrieved from the returned copy of the object.

    for example

     #include <iostream> #include <algorithm> #include <iterator> struct S { int sum = 0; void operator()(int i) { sum += i; } }; int main(void) { int a[] = { 1, 2, 3, 4, 5 }; std::cout << std::for_each(std::begin(a), std::end(a), S()).sum << std::endl; } 

    The situation can also be considered from the point of view of the same design idiom, which is present in classical C-functions like strcpy , i.e. the passed-through value can also be used for a more compact (concatenated) recording of consecutive calls to std::for_each with the same (in terms of value) functional object

     int main(void) { int a[] = { 1, 2, 3, 4, 5 }; int b[] = { 6, 7, 8, 9, 10 }; int c[] = { 11, 12, 13, 14, 15 }; std::cout << std::for_each(std::begin(c), std::end(c), std::for_each(std::begin(b), std::end(b), std::for_each(std::begin(a), std::end(a), S()))).sum << std::endl; } 
    • Dear AnT, please tell me what you see the advantage of this method over a much more visual for? Additionally, the declared structure + a long and difficult to understand string for_each + 2 libraries. Are the overheads too big ?, - BuilderC