STLalgorithm算法count_if(11)
原文地址:http://www.cplusplus.com/reference/algorithm/count\_if/
function template
std::count_if
template <class InputIterator, class Predicate>
typename iterator_traits
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
Return number of elements in range satisfying condition
Returns the number of elements in the range [first,last)
for which pred is true.
返回范围内对每个元素调用pred返回true的次数。例子:
#include
#include
#include
#include
using namespace std;
bool ismod2(int i){
return i%2==0;
}
void countif(){
vector
array<int,7> ai{888,666,555,222,111,555,777};
cout<<”vi=”;
for(int &i:vi)
cout<<i<<” “;
cout<<endl;
int cv=count\_if(vi.begin(),vi.end(),ismod2);
cout<<"能被2整除的一共有"<<cv<<"个"<<endl;
cout<<"ai=";
for(int &i:ai)
cout<<i<<" ";
cout<<endl;
int ca=count\_if(ai.begin(),ai.end(),\[\](int i){return i>500;});
cout<<"大于500的一共有"<<ca<<"个"<<endl;
}
运行截图:
The behavior of this function template is equivalent to:
1 | 1 |
1 | template <class InputIterator, class UnaryPredicate> |
Parameters
first, last
Input iterators to the initial and final positions of the sequence of elements. The range used is [first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
元素的范围。
pred
Unary function that accepts an element in the range as argument, and returns a value convertible to bool
. The value returned indicates whether the element is counted by this function.
The function shall not modify its argument.
This can either be a function pointer or a function object.
接受一个元素作为参数兵返回一个bool值的一元函数。
Return value
The number of elements in the range [first,last)
for which pred does not return false
.
The return type (iterator_traits
返回范围内对每个元素调用pred返回true的次数。
Example
1 | 1 |
1 | // count_if example |
Output:
myvector contains 5 odd values.
Complexity
Linear in the distance between first and last: Calls pred once for each element.
Data races
The objects in the range [first,last)
are accessed (each object is accessed exactly once).
Exceptions
Throws if pred trhows or if any of the operations on iterators throws.
Note that invalid arguments cause undefined behavior.
——————————————————————————————————————————————————————————————————
//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。
转载请注明出处:http://blog.csdn.net/qq844352155
author:天下无双
Email:coderguang@gmail.com
2014-9-11
于GDUT
——————————————————————————————————————————————————————————————————
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/stlalgorithm算法count-if11/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!