📜  C++ STL-algorithm.count_if()函数

📅  最后修改于: 2020-10-16 08:00:29             🧑  作者: Mango

C++ STL algorithm函数count_if()

C++ STL algorithm.count_if()函数具有’pred’值,并返回pred值为true的[first,last)范围内的元素计数。

句法

template 

typename iterator_traits::difference_type count_if(InputIterator first, InputIterator last,UnaryPredicate pred);

参数

first:它是范围中第一个元素的输入迭代器。

last:它是范围中最后一个元素的输入迭代器。

val:在范围内搜索其出现的元素。

返回值

该函数返回pred值为true的[first,last)范围内的元素数。

例子1

#include
#include
#include
bool isOdd(int k)
{
    return((k%2)==1);
}
int main()
{
    std::vector newvector;
    for(int k=1; k<10; k++)
    newvector.push_back(k);
    int newcount=count_if(newvector.begin(),newvector.end(),isOdd);
    std::cout<<"newvector contains "<

输出:

newvector contains 5 odd values.

例子2

#include
using namespace std;
bool isEven(int k)
{
    if(k%2==0)
    return true;
}
int main()
{
    vector u;
    for(int i=0; i<10; i++)
    {
        u.push_back(i);
    }
    int noEven=count_if(u.begin(),u.end(),isEven);
    cout<<"Count of even number is:"<

输出:

Count of even number is: 10

复杂度

函数的复杂度是线性的,直到第一个元素和最后一个元素之间的距离为止。

数据竞争

访问范围的部分或全部元素

异常处理

如果任何参数抛出一个异常,该函数将引发异常。