std::bitset<N>::count

From cppreference.com
< cpp‎ | utility‎ | bitset
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)
 
 
std::size_t count() const;
(until C++11)
std::size_t count() const noexcept;
(since C++11)
(until C++23)
constexpr std::size_t count() const noexcept;
(since C++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 <iostream>
#include <bitset>
 
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)
(C++20)
counts the number of 1 bits in an unsigned integer
(function template)