c – 将std :: count_if更快没有一个if?

前端之家收集整理的这篇文章主要介绍了c – 将std :: count_if更快没有一个if?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是 gcc std :: count_if代码 @H_502_2@template<typename _InputIterator,typename _Predicate> typename iterator_traits<_InputIterator>::difference_type count_if(_InputIterator __first,_InputIterator __last,_Predicate __pred) { [snip] typename iterator_traits<_InputIterator>::difference_type __n = 0; for (; __first != __last; ++__first) if (__pred(*__first)) ++__n; return __n; }

我的问题:它会更好地工作(即更快)使用

@H_502_2@__n += __pred(*__first); // instead of the if statement

这个版本总是做一个添加,但不做一个分支.

解决方法

你给的替换不是等同的,因为对谓词的限制比你想象的要少得多:

>可以在条件上下文中使用的任何东西(可以上下文转换为bool)是谓词的有效返回类型(对bool的显式转换就足够了).
>那个返回类型可以反应有趣,被添加到迭代器的差异类型.

25 Algorithms library [algorithms]

25.1 General [algorithms.general]

8 The Predicate parameter is used whenever an algorithm expects a function object (20.9) that,when applied to the result of dereferencing the corresponding iterator,returns a value testable as true. In other words,if an algorithm takes Predicate pred as its argument and first as its iterator argument,it should work correctly in the construct pred(*first) contextually converted to bool (Clause 4). The function object pred shall not apply any non-constant function through the dereferenced iterator.

最有可能的退回给您的替代消化不良将是一个标准的整型类型,值不为0和1.

另外,请记住,编译器实际上可以优化当今的优势(特别是C需要,所有这些模板的东西分层深).

原文链接:https://www.f2er.com/c/113994.html

猜你在找的C&C++相关文章