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]@H_502_20@
25.1 General
[algorithms.general]@H_502_20@
8 The
Predicate@H_502_20@ 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@H_502_20@. In other words,if an algorithm takes
Predicate pred@H_502_20@ as its argument and
first@H_502_20@ as its iterator argument,it should work correctly in the construct
pred(*first)@H_502_20@ contextually converted to
(Clause 4). The function objectbool@H_502_20@
pred@H_502_20@ shall not apply any non-constant function through the dereferenced iterator.
最有可能的退回给您的替代消化不良将是一个标准的整型类型,值不为0和1.
另外,请记住,编译器实际上可以优化当今的优势(特别是C需要,所有这些模板的东西分层深).