具有cmath函数的stl方法

JSc*_*her 4 c++ stl

我试图编写一个STL方法来获取向量的日志:

for_each(vec.begin(),vec.end(),log);
Run Code Online (Sandbox Code Playgroud)

但我明白了

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>)’
Run Code Online (Sandbox Code Playgroud)

我收集的是由于日志功能的多个版本.显然我可以在日志函数周围编写一个简单的包装器并用它调用它.有没有更简单的方法来指定我想要内联的日志功能?

jpa*_*cek 8

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

for_each(vec.begin(),vec.end(),(double(*)(double))log);
Run Code Online (Sandbox Code Playgroud)

另一种可能性是创建可以接受任何类型的仿函数:

struct log_f
{
  template <class T> T operator()(const T& t) const { return log(t); }
};

for_each(vec.begin(),vec.end(), log_f());
Run Code Online (Sandbox Code Playgroud)

而且,正如Billy O'Neal指出的那样,你想要而transform不是for_each.

  • 这是`static_cast`.中间的`(*)`表示指针.即.`void(int)`是一种函数类型,它接受一个`int`并且什么都不返回,`void(*)(int)`是一个指向该函数的指针.`void*(int)`将是一个函数(不是指针),它接受一个`int`并返回一个void-pointer. (2认同)