quoting from "The C++ Standard Library" by N M Jousttis, Section 5.9
#include < iostream>
#include < list>
#include < algorithm>
using namespace std;
//function object that adds the value with which it is initialized
class AddValue {
private:
int the Value; //the value to add
public:
//constructor initializes the value to add
AddValue(int v) : theValue(v) { }
//the "function call" for the element adds the value
void operator() (int& elem) const { elem += theValue; }
};
int main()
{
list<int> coll;
for (int i=1; i<=9; ++i)
coll.push_back(i);
//The first call of for_each() adds 10 to each value:
for_each (coll.begin(), coll.end(), AddValue(10)) ;
Here, the expression AddValue(10) creates an object of type AddValue that is initialized with the value 10. The constructor of AddValue stores this value as the member theValue. Inside for_each(), "()" is called for each element of coll. Again, this is a call of operator () for the passed temporary function object of type AddValue. The actual element is passed as an argument. The function object adds its value 10 to each element. The elements then have the following values: after adding 10:
11 12 13 14 15 16 17 18 19
The second call of for_each() uses the same functionality to add the value of the first element to each element. It initializes a temporary function object of type AddValue with the first element of the collection:
for_each (coll.begin(), coll.end(), AddValue (*coll. begin()) ) ;
The output is then as follows after adding first element:
22 23 24 25 26 27 28 29 30
what I don't understand is in the second case why is the output is not
22 34 35 36 37 38 39 40 41
meaning is a new functor being created for each call or is the functor used for each call ?