加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:42:08 所属栏目:百科 来源:网络整理
导读:这是 gcc std :: count_if代码 templatetypename _InputIterator,typename _Predicate typename iterator_traits_InputIterator::difference_type count_if(_InputIterator __first,_InputIterator __last,_Predicate __pred) { [snip] typename iterator_tr
这是 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需要,所有这些模板的东西分层深).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读