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需要,所有这些模板的东西分层深).

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...