bitset::count() is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number.
Syntax:
int count()
Parameter: The function accepts no parameter.
Return Value: The function returns the number of set bits. It returns the total number of ones or the number of set bits in the binary representation of the number if the passed number is an integer.
Below programs illustrates the bitset::count() function.
Program 1:
// CPP program to illustrate the // bitset::count() function #include <bits/stdc++.h> using namespace std; int main() { // Initialisation of a bitset bitset<4> b1(string("1100")); bitset<6> b2(string("001000")); // Function to count the // number of set bits in b1 int result1 = b1.count(); cout << b1 << " has " << result1 << " set bit\n"; // Function to count the // number of set bits in b2 int result2 = b2.count(); cout << b2 << " has " << result2 << " set bit"; return 0; } |
1100 has 2 set bit 001000 has 1 set bit
Program 2:
// CPP program to illustrate the // bitset::count() function // when the input is an integer #include <bits/stdc++.h> using namespace std; int main() { // Initialisation of a bitset bitset<4> b1(16); bitset<4> b2(18); // Function to count the // number of set bits in b1 int result1 = b1.count(); cout << b1 << " has " << result1 << " set bit\n"; // Function to count the // number of set bits in b2 int result2 = b2.count(); cout << b2 << " has " << result2 << " set bit"; return 0; } |
0000 has 0 set bit 0010 has 1 set bit
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
Recommended Posts:
- std::bitset::to_ullong and std::bitset::to_ulong in C++ STL
- bitset::flip() in C++ STL
- bitset all() function in C++ STL
- bitset set() function in C++ STL
- bitset reset() function in C++ STL
- bitset test() in C++ STL
- bitset none() in C++ STL
- bitset any() in C++ STL
- bitset operator[] in C++ STL
- bitset size() in C++ STL
- Count number of set bits in a range using bitset
- Count number of common elements between two arrays by using Bitset and Bitwise operation
- C++ bitset and its application
- Subset sum queries using bitset
- C++ bitset interesting facts
- _Find_first() function in C++ bitset with Examples
- _Find_next() function in C++ bitset with Examples
- std::count() in C++ STL
- Count the number of 1's and 0's in a binary array using STL in C++ ?
- Count smaller elements on right side using Set in C++ STL
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.

