使用C++ STL查詢陣列中奇數和偶數元素
給定一個數組,任務是使用C++標準模板庫查詢陣列中奇數和偶數元素的個數。
為了解決這個問題,我們使用C++標準模板庫中的`count_if()`函式。什麼是`count_if()`函式?
語法
count_if(LowerBound, UpperBound, function)
**描述** − 此函式返回陣列中滿足給定條件的元素個數。它接受三個引數。
- **下界** − 它指向陣列或任何其他序列的第一個元素。
- **上界** − 它指向陣列或任何其他序列的最後一個元素。
- **函式** − 根據指定的條件返回布林值。
示例
Input-: array[] = {2, 4, 1, 5, 8, 9} Output-: Odd elements are: 1, 5 and 9. So, total number of odds is 3 Even elements are: 2, 4 and 8 Input-: array[] = {1, 2, 3, 4, 5, 10} Output-: Odd elements are: 1, 3 and 5. So, total number of odds is 3 Even elements are: 2, 4 and 10. So, total number of evens is 3
**下面程式中使用的方案如下** −
- 將整數值輸入到整型陣列中
- 建立布林函式以檢查陣列元素是否為奇數。如果選擇的元素為奇數,則其餘元素將為偶數。
- 呼叫`count_if()`函式,該函式將第一個元素、最後一個元素和函式作為引數。
示例
#include <bits/stdc++.h> using namespace std; // Function to check if the element is odd or even bool check(int i) { if (i % 2 != 0) return true; else return false; } int main() { int arr[] = { 2, 10, 1, 3, 7, 4, 9 }; int size = sizeof(arr) / sizeof(arr[0]); int temp = count_if(arr, arr + size, check); cout << "Odds are : " <<temp << endl; cout << "Evens are : " << (size - temp) << endl; return 0; }
輸出
如果我們執行上述程式碼,它將生成以下輸出:
Odds are: 4 Evens are: 3
廣告