// Function object - functor - taking cosine of // elementes and summing them up #include #include #include #include using namespace std; class TakeCos{ double sum; public: //function object double operator()(double& x){ x = cos(x); // must change element x! sum += x; return x; } TakeCos() : sum(0.0){} // zero sum at construction double getsum() { return sum; } }; void doubleout(double& x) { cout<< x<<" ";} void vector_out(vector & x){ for_each (x.begin(), x.end(), doubleout); cout< x; x.push_back(1.1); x.push_back(2.2); x.push_back(3.3); cout << "vector x : "; vector_out(x); // for_each works with a copy of Cos, // so I need to store that copy to Cosx to get out the sum as Cosx.sum TakeCos Cos; TakeCos Cosx = for_each(x.begin(), x.end(), Cos); cout << "vector cos(x) : "; vector_out(x); cout<<"sum = "<