使用 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP