如何使用isnan作为谓词函数std :: find

编程入门 行业动态 更新时间:2024-10-10 21:22:35
本文介绍了如何使用isnan作为谓词函数std :: find_if(c ++ 11)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个操作在 std :: vector< double> cats ,并且正在这样做:

I have a piece of code that is operating on a std::vector<double> cats and is doing something like this:

std::find_if(cats.begin(), cats.end(), std::isnan<double>);

这是在4.3之前的gcc下编译,但不再使用gcc 4.7.2编译。我得到这样的错误:

this compiles under gcc before 4.3 but no longer compiles with gcc 4.7.2. I get an error like this:

error: no matching function for call to 'find_if(std::vector<double>::iterator, std::vector<double::iterator, <unresolved overloaded function type>)'

我如何得到这个在新的gcc下编译?最好还是在老gcc下?没有摆脱stl和手动写循环当然。如果不可能做到这两者,新的gcc就足够了,我会使用 #define 保留两个实现。

How can I get this to compile under newer gcc? And preferably also under the older gcc? Without getting rid of stl and manually writing the loop of course. If it's not possible to do both, the new gcc would suffice and I would leave both implementations in there with a #define.

推荐答案

实际需要的重载不是GCC 4.7中的模板,它只是一个带有这个签名的普通函数:

The overload you actually want is not a template in GCC 4.7, it is just a normal function with this signature:

bool isnan(double);

(有一个模板,但SFINAE意味着它只适用于整数类型。)

(There is a template, but SFINAE means it only applies to integral types.)

但是在以前的版本中,它是一个模板,所以没有一个简单的便携式方式来获取它的地址。

But in previous versions it was a template, so there isn't an easy portable way to take its address.

你已经说过C ++ 11,你可以使用一个lambda,并让lambda的主体做重载决议找到正确的重载(或模板专业化):

Since you've said C++11, you can use a lambda and let the body of the lambda do overload resolution to find the right overload (or template specialization):

std::find_if( cats.begin(), cats.end(), [](double d) { return std::isnan(d); } );

否则对于C ++ 03你可以提供自己的转发包装:

Otherwise for C++03 you could provide your own forwarding wrapper:

struct IsNan { double operator()(double d) const { return std::isnan(d); } }; std::find_if( cats.begin(), cats.end(), IsNan() );

更多推荐

如何使用isnan作为谓词函数std :: find

本文发布于:2023-11-30 14:34:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650341.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:谓词   如何使用   函数   find   isnan

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!