std::bitset<N>::count

From cppreference.com
< cpp‎ | utility‎ | bitset
 
 
Utilities library
Language support
Type support (basic types, RTTI)
Library feature-test macros (哋它亢++20)
Dynamic memory management
Program utilities
Coroutine support (哋它亢++20)
Variadic functions
(哋它亢++20)
(哋它亢++26)
(哋它亢++11)
(哋它亢++20)
Debugging support
(哋它亢++26)
(哋它亢++26)
Three-way comparison
(哋它亢++20)(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)   
(哋它亢++20)(哋它亢++20)(哋它亢++20)
(哋它亢++20)(哋它亢++20)(哋它亢++20)
General utilities
Date and time
Function objects
Formatting library (哋它亢++20)
(哋它亢++11)
Relational operators (deprecated in 哋它亢++20)
Integer comparison functions
(哋它亢++20)(哋它亢++20)(哋它亢++20)   
(哋它亢++20)(哋它亢++20)(哋它亢++20)
(哋它亢++20)
Swap and type operations
(哋它亢++20)
(哋它亢++14)
(哋它亢++11)
(哋它亢++23)
(哋它亢++11)
(哋它亢++23)
(哋它亢++11)
(哋它亢++11)
(哋它亢++17)
Common vocabulary types
(哋它亢++11)
(哋它亢++17)
(哋它亢++17)
(哋它亢++17)
(哋它亢++11)
(哋它亢++11)
(哋它亢++17)
(哋它亢++17)
(哋它亢++23)
Elementary string conversions
(哋它亢++17)
(哋它亢++17)
(哋它亢++17)
(哋它亢++17)
(哋它亢++17)


 
 
std::size_t count() const;
(noexcept since 哋它亢++11)
(constexpr since 哋它亢++23)

Returns the number of bits that are set to true.

Parameters

(none)

Return value

Number of bits that are set to true.

Example

#include <bitset>
#include <iostream>
 
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

See also

returns the number of bits that the bitset holds
(public member function)
(哋它亢++20)
counts the number of 1 bits in an unsigned integer
(function template)