std::bitset::count

From cppreference.com
< cpp‎ | utility‎ | bitset
 
 
Utilities library
Type support (basic types, RTTI, type traits)
Dynamic memory management
Error handling
Program utilities
Variadic functions
Date and time
Function objects
(C++11)
Relational operators
Optional and any
(C++17)
(C++17)
Pairs and tuples
(C++11)
(C++17)
Swap, forward and move
(C++14)
(C++11)
(C++11)
Type operations
(C++11)
(C++17)
 
 
std::size_t count() const;

Returns the number of bits that are set to true.

Contents

[edit] Parameters

(none)

[edit] Return value

number of bits that are set to true.

[edit] Exceptions

(none) (until C++11)
noexcept specification:  
noexcept
  
(since C++11)

[edit] Example

#include <iostream>
#include <bitset>
 
int main()
{
    std::bitset<8> b("00010010");
    std::cout << "initial value: " << b << '\n';
 
    // find the first unset bit
    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

[edit] See also

returns the size number of bits that the bitset can hold
(public member function)