使用 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.