Count the number of 1’s and 0’s in a binary array using STL in C++ ?
Given a binary array, the task is to count the number of 1’s and 0’s in this array using STL in C++.
Examples:
Input: arr[] = {1, 0, 0, 1, 0, 0, 1}
Output: 1's = 3, 0's = 4
Input: arr[] = {1, 1, 1, 1, 0, 0, 1}
Output: 1's = 5, 0's = 2
Approach: We can count the same using count_if() function present in the STL of C++.
Syntax:
count_if(lower_bound, upper_bound, filter_function) where filter_function is a condition which filters out elements.
Below is the implementation of the above approach:
// C++ program to Count // the number of 1's and 0's // in a binary array #include <bits/stdc++.h> using namespace std; // Function to check // if bit is 1 or not bool isOne(int i) { if (i == 1) return true; else return false; } // Driver Code 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; } |
chevron_right
filter_none
Output:
1's: 3 0's: 4
Recommended Posts:
- Count number of triplets in an array having sum in the range [a, b]
- Minimum sub-array such that number of 1's in concatenation of binary representation of its elements is at least K
- Count smaller elements in sorted array in C++
- Count pairs whose products exist in array
- Count Hexadecimal Number
- Count number of unique Triangles using STL | Set 1 (Using set)
- Occurrences of a pattern in binary representation of a number
- Count Numbers with N digits which consists of odd number of 0's
- Count of Numbers such that difference between the number and sum of its digits not less than L
- How to count set bits in a floating point number in C?
- Count the number of words having sum of ASCII values less than and greater than k
- Count the number of objects using Static member function
- Count subarrays with equal number of occurrences of two given elements
- Count the number of rhombi possible inside a rectangle of given size
- Program to count Number of connected components in an undirected graph
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



