In this tutorial, we will be discussing a program to count the number of 1’s and 0’s in a binary array using STL in C++.
For this we will be provided with an array. Our task is to count the number of 0’s and 1’s present in the array.
Example
#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;
}Output
1's: 3 0's: 4