1. 认识count_if(a1, a2, far)
count_if()
函数是一个算术函数,所以需要一个头文件:
include< algorithm >
count_if()
函数的功能 是对指定区域中符合指定条件计数的一个函数
(返回所有满足条件为true的数字累计)。
这个函数接受一对迭代器(表示输入一个范围: 也就是 “a1”:是你要选择范围的开始位置,
“a2 ”:是你想要范围结尾的位置);第三个参数应是一个返回true 或false 的函数对象(far)( 函数指针| 谓词)。
直接看代码解释:
bool f3(int n){ return n % 3 == 0; }
vector<int> number(100);//创建一个数组(容器)
//begin() || end() 是迭代器
int count = count_if( number.begin() , number.end(), f3 );
// count_if ( 区域1,区域2, 函数对象(指针) f3----是函数名,是一个指针。
f3 是一个函数名,函数名是指针。 程序运行后,会将数组 number.begin()
到number.end()
区间里面的数导入到 f3 这个函数里面作为参数, 最终函数会判断是否为 true ,是的话会统计所有结果为true的数并返回。
下面是源代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool f3(int n)
{
return n % 3 == 0;
}
int main()
{
vector<int> number(100);//创建一个数组(也可以认为是一个迭代器)begin() || end() 是迭代器的函数
for(int i = 0; i < 100; i++)
{
number[i] = i;
}
int count = count_if( number.begin() , number.end(), f3 );// count_if ( 区域1,区域2, 函数对象(指针) f3----是函数名,是一个指针。
//f3()----是函数。
cout << "有 " << count << "个数可以被 3 整除 。" << endl;
return 0;
}
这就是我查资料结合我的理解所表达的内容,可能不完整或者有错误请大家指出来,谢谢大家。
更多推荐
C++中 count_if()函数的讲解
发布评论