具有 cmath 函数的 Stl 方法

发布于 2024-09-12 22:05:15 字数 511 浏览 2 评论 0原文

我试图编写一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温折酒 2024-09-19 22:05:15

是的。您可以将函数转换为适当的类型:

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

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

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

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

并且,正如 Billy O'Neal 指出的那样,您需要 transform 而不是 for_each< /代码>。

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.

ゝ杯具 2024-09-19 22:05:15

我相信 std::for_each 正在寻找具有 void 返回类型的函数。您正在传递一个具有双返回类型的函数。 jpalecek 的答案是正确的,并为他+1。但是,您仍然存在语义问题,即对 log 进行 for_each 没有任何意义:

如果您希望向量的所有成员都是先前成员的对数,即:

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

那么您就不需要不需要for_each,你需要transform

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

I believe std::for_each is looking for a function with a void return type. You're passing a function with a double return type. jpalecek's answer is the correct one, and +1 to him. However, you still have the semantic issue that doing 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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文