Stl methods with cmath functions

I tried to write an STL method to take a vector log:

for_each(vec.begin(),vec.end(),log); 

But I get

 no matching function for call to 'for_each(__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >, __gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >, <unresolved overloaded function type>)' 

Which I am going to due to the log function of several versions. Obviously, I can write a simple wrapper around the log function and call it that. Is there an easier way to specify which log function I want to use?

+4
source share
2 answers

Yes. You can apply the function to the appropriate type:

 for_each(vec.begin(),vec.end(),(double(*)(double))log); 

Another possibility is to create your functor that will accept any type:

 struct log_f { template <class T> T operator()(const T& t) const { return log(t); } }; for_each(vec.begin(),vec.end(), log_f()); 

And, as Billy O'Neill pointed out, you need to transform rather than for_each .

+8
source

I believe std::for_each looking for a function with a return type of void. You pass a function with a double return type. Jpalecek's answer is correct, but +1 to him. However, you still have a semantic problem that doing for_each with the log makes no sense:

If you want all the members of the vector to be a journal of the previous members, that is:

 //pseudocode foreach( var x in myvector ) x = log(x); 

Then you do not want for_each , you want transform .

 std::transform(vec.begin(), vec.end(), vec.begin(), log); 
+2
source

All Articles