使用 C++ 中的 STL 計算二進位制陣列中 1 和 0 的數量
在本文中,我們將討論一個程式,使用 C++ 中的 STL 來計算二進位制陣列中 1 和 0 的數量。
為此,我們將提供一個數組。我們的任務是計算陣列中存在的 0 和 1 的數量。
示例
#include <bits/stdc++.h> using namespace std; // checking if element is 1 or not bool isOne(int i){ if (i == 1) return true; else return false; } int main(){ int a[] = { 1, 0, 0, 1, 0, 0, 1 }; int n = sizeof(a) / sizeof(a[0]); int count_of_one = count_if(a, a + n, isOne); cout << "1's: " << count_of_one << endl; cout << "0's: " << (n - count_of_one) << endl; return 0; }
輸出
1's: 3 0's: 4
廣告