微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

这是 gcc std :: count_if代码
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;
}

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

__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.jb51.cc/c/113994.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐