Stl methods with cmath functions
I was trying to write an STL meth开发者_如何学运维od 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?
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
.
I believe jpalecek's answer is the correct one, and +1 to him. However, you still have the semantic issue that doing std::for_each
is looking for a function with a void return type. You're passing a function with a double return type.for_each
with log doesn't make any sense:
If you want all the members of the vector to be the log of the previous members, i.e.:
//pseudocode
foreach( var x in myvector )
x = log(x);
Then you don't want for_each
, you want transform
.
std::transform(vec.begin(), vec.end(), vec.begin(), log);
精彩评论