C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ count_if()

C++ 算法函数count_if()

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

语法

template <class InputIterator, class UnaryPredicate>
typename iterator_traits<InputIterator>::difference_type count_if(InputIterator first, InputIterator last,UnaryPredicate pred);

参数

first: 它是范围中第一个元素的输入迭代器。
last: 它是范围中last元素的输入迭代器。
val : 它是在范围中正在搜索其出现的元素。

返回值

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

示例1

#include<iostream>
#include<algorithm>
#include<vector>
bool isOdd(int k)
{
    return((k%2)==1);
}
int main()
{
    std::vector<int> 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 "<<newcount<<" odd values.\n";
    return 0;
}
输出:
newvector contains 5 odd values.

示例2

#include<bits/stdc++.h>
using namespace std;
bool isEven(int k)
{
    if(k%2==0)
    return true;
}
int main()
{
    vector<int> 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:"<<noEven;
    return 0;
}
输出:
Count of even number is: 10

复杂度

该函数的复杂度与第一个元素和last元素之间的距离呈线性关系。

数据竞争

访问范围中的某些或全部元素

异常

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

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4