std::count_if() 函数在 C++ STL 中
在本文中,我们将讨论 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 给出范围的结束位置。
- condition - 这是我们要检查的条件。Condition 是必须应用于给定范围的一元函数。
返回值
此函数返回满足条件的元素数量。
示例
输入
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP