具有 cmath 函数的 Stl 方法
我试图编写一个 STL 方法来获取向量的对数:
for_each(vec.begin(),vec.end(),log);
但我得到的
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>)’
是,我收集的是由于对数函数的多个版本。显然,我可以围绕日志函数编写一个简单的包装器并用它来调用它。有没有更简单的方法来指定我想要内联的日志函数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。您可以将函数转换为适当的类型:
另一种可能性是创建接受任何类型的函子:
并且,正如 Billy O'Neal 指出的那样,您需要
transform
而不是for_each< /代码>。
Yes. You can cast the function to the appropriate type:
Another possibility would be creating your functor that would accept any type:
And, as Billy O'Neal pointed out, you want rather
transform
thanfor_each
.我相信jpalecek 的答案是正确的,并为他+1。但是,您仍然存在语义问题,即对 log 进行std::for_each
正在寻找具有 void 返回类型的函数。您正在传递一个具有双返回类型的函数。for_each
没有任何意义:如果您希望向量的所有成员都是先前成员的对数,即:
那么您就不需要不需要
for_each
,你需要transform
。I believejpalecek's answer is the correct one, and +1 to him. However, you still have the semantic issue that doingstd::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.:
Then you don't want
for_each
, you wanttransform
.