给定一个数组,任务是使用C ++中的标准模板库查找N可以整除的数字。
为了解决此问题,我们使用C ++标准模板库中提供的count_if()函数。
什么是count_if()函数?
count_if(LowerBound, UpperBound, function)
描述-此函数返回满足给定条件的数组中的元素数。它包含三个参数。
下界-指向数组或任何其他序列的第一个元素。
上限-指向数组或任何其他序列的最后一个元素。
功能-它根据指定的条件返回布尔值。
Input-: array[] = {2, 4, 1, 5, 8, 9}
N = 4
Output-: Elements divisible by 4: 2
Input-: array[] = {1, 2, 3, 4, 5, 10}
N = 2
Output: Elements divisible by 2: 3以下程序中使用的方法如下-
在整数类型的数组中输入整数值。
创建布尔函数以检查数组的元素是否可被用户输入值N整除。
调用函数count_if(),该函数将第一个和最后一个元素以及该函数作为参数。
#include <bits/stdc++.h>
using namespace std;
int n;
//函数检查元素是否可以被n整除
bool check(int i) {
if (i % n == 0)
return true;
else
return false;
}
int main() {
int arr[] = {2, 4, 1, 5, 8, 9};
n = 4;
int size = sizeof(arr) / sizeof(arr[0]);
int temp = count_if(arr, arr + size, check);
cout<<"Elements divisible by "<<n<< ": " <<temp;
return 0;
}输出结果
如果我们运行上面的代码,它将生成以下输出-
Elements divisible by 4: 2