Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stl methods with cmath functions

Tags:

c++

stl

I was trying to write an STL method to take the log of a vector:

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 gather is due to log function's multiple versions. Obviously I can write a simple wrapper around the log function and call it with that. Is there a simpler way to specify which log function I want inline?

like image 260
JSchlather Avatar asked Dec 29 '22 09:12

JSchlather


1 Answers

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

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

Another possibility would be creating your functor that would 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'Neal pointed out, you want rather transform than for_each.

like image 168
jpalecek Avatar answered Jan 13 '23 06:01

jpalecek