count_if
返回中元素的数目。值满足指定条件范围的。
template<class InputIterator, class Predicate>
typename iterator_traits<InputIterator>::difference_type count_if(
InputIterator _First,
InputIterator _Last,
Predicate _Pred
);
参数
_First
处理第一元素位置的输入迭代器在要搜索的范围。_Last
寻址最终元素的输入迭代器位置一个要搜索的范围。_Pred
定义将满足的条件的用户定义谓词函数的对象元素,则将计数。 谓词采用单个参数并返回 true 或 false。
返回值
满足条件元素的数量谓词所指定。
备注
此模板是函数 count算法泛化,替换谓词“等于特定值”与所有谓词。
示例
// alg_count_if.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <iostream>
bool greater10(int value)
{
return value >10;
}
int main()
{
using namespace std;
vector<int> v1;
vector<int>::iterator Iter;
v1.push_back(10);
v1.push_back(20);
v1.push_back(10);
v1.push_back(40);
v1.push_back(10);
cout << "v1 = ( ";
for (Iter = v1.begin(); Iter != v1.end(); Iter++)
cout << *Iter << " ";
cout << ")" << endl;
vector<int>::iterator::difference_type result1;
result1 = count_if(v1.begin(), v1.end(), greater10);
cout << "The number of elements in v1 greater than 10 is: "
<< result1 << "." << endl;
}
要求
标头: <算法>
命名空间: std