使用C ++中的STL计算二进制数组中1和0的数量

在本教程中,我们将讨论一个程序,该程序使用C ++中的STL对二进制数组中的1和0进行计数。

为此,我们将提供一个数组。我们的任务是计算数组中存在的0和1的数量。

示例

#include <bits/stdc++.h>

using namespace std;

//检查元素是否为1-

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

以上是 使用C ++中的STL计算二进制数组中1和0的数量 的全部内容, 来源链接: utcz.com/z/322429.html

回到顶部