std::bitset<N>::count
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Utilities library
Type support (basic types, RTTI)
Library feature-test macros (C++20)
(C++11)
(C++20)
(C++26)
(C++20)
Coroutine support (C++20)
Contract support (C++26)
(C++20)(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
General utilities
Relational operators (deprecated in C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
(C++20)
Swap and type operations
Common vocabulary types
std::bitset
(until C++20)
bitset::count
(C++11)
(C++11)
Returns the number of bits that are set to true.
[edit] Return value
Number of bits that are set to true.
[edit] Example
Run this code
#include <bitset> #include <iostream> constexpr auto popcount(unsigned x) noexcept { unsigned num{}; for (; x; ++num, x &= (x - 1)); return num; } static_assert(popcount(0b101010) == std::bitset <8>{0b101010}.count()); int main() { std::bitset <8> b("00010010"); std::cout << "Initial value: " << b << '\n'; // Find the first unset bit std::size_t idx = 0; while (idx < b.size() && b.test(idx)) ++idx; // Continue setting bits until half the bitset is filled while (idx < b.size() && b.count() < b.size() / 2) { b.set(idx); std::cout << "Setting bit " << idx << ": " << b << '\n'; while (idx < b.size() && b.test(idx)) ++idx; } }
Output:
Initial value: 00010010 Setting bit 0: 00010011 Setting bit 2: 00010111