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

更新時間:2020 年 3 月 16 日

332 瀏覽量

開啟您的職業生涯

完成課程即可獲得認證

開始學習
廣告