C ++ STL中的count_if()

在本文中,我们将讨论C ++ STL中std::count_if()函数的工作,语法和示例。

什么是std::count_if()?

std::count_if()函数是C ++ STL中的内置函数,在<algorithm>头文件中定义。count_if()用于获取指定范围内满足条件的元素数。该函数返回一个整数值,该整数值是满足条件的元素数。

该函数不仅遍历给定范围,还检查语句或条件是否为真,并计数该语句或条件为真的次数并返回结果。

语法

count_if(start, end, condition);

参数

该函数接受以下参数-

  • start,end-这些是迭代器,可用于提供我们必须使用该函数的范围。start给出范围的开始位置,end给出范围的结束位置。

  • 条件-这是我们要检查的条件。条件是一元函数,必须将其应用于给定范围。

返回值

此函数返回满足条件的元素数。

示例

输入值

bool iseve(int i){ return ((i%2)==0); }
int a = count_if( vect.begin(), vect.end(), iseve ); /* vect has 10 integers 1-10*/

输出结果

even numbers = 2 4 6 8 10

示例

#include <bits/stdc++.h>
using namespace std;
bool check_odd(int i){
   if (i % 2!= 0)
      return true;
   else
      return false;
}
 int main() {
   vector<int> vec;
   for (int i = 0; i < 10; i++){
      vec.push_back(i);
   }
   int total_odd = count_if(vec.begin(), vec.end(), check_odd);
   cout<<"Number of odd is: "<<total_odd;
   return 0;
}

输出结果

Number of odd is: 5