这是 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
就够了)。 - 该返回类型对添加到迭代器差异类型的 react 很有趣。
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 astrue
. In other words, if an algorithm takesPredicate pred
as its argument andfirst
as its iterator argument, it should work correctly in the constructpred(*first)
contextually converted tobool
(Clause 4). The function objectpred
shall not apply any non-constant function through the dereferenced iterator.
最有可能给你的替代消化不良的返回是一个标准的整数类型,一个既不是 0 也不是 1 的值。
另外,请记住,如今编译器实际上可以非常好地进行优化(尤其是 C++ 编译器需要这样做,所有这些模板内容都分层得很深)。
关于c++ - 如果没有 if,std::count_if 会更快吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26245969/