使用 C++ STL 查找数组中可被 N 整除的元素


给定一个数组,任务是使用 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;
//function to check if the element is divisible by 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

更新于: 2020年1月20日

179 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.