Namespaces
Variants

std::bitset<N>::count

Von de.cppreference.net
 
 
Dienstprogrammbibliothek
Sprachunterstützung
Typunterstützung (Basistypen, RTTI)
Bibliotheks-Feature-Test-Makros (C++20)
Programm-Dienstprogramme
Variadische Funktionen
Koroutinen-Unterstützung (C++20)
Vertragsunterstützung (C++26)
Drei-Wege-Vergleich
(C++20)
(C++20)(C++20)(C++20)    
(C++20)(C++20)(C++20)

Allgemeine Dienstprogramme
Relationsoperatoren (veraltet in C++20)
Ganzzahl-Vergleichsfunktionen
(C++20)(C++20)(C++20)    
(C++20)
Tausch und Typoperationen
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Allgemeine Vokabular-Typen
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



 
 
std::size_t count() const;
(noexcept seit C++11)
(constexpr seit C++23)

Gibt die Anzahl der Bits zurück, die auf true gesetzt sind.

Rückgabewert

Anzahl der Bits, die auf true gesetzt sind.

Beispiel

#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;
    }
}

Ausgabe:

Initial value: 00010010
Setting bit 0: 00010011
Setting bit 2: 00010111

Siehe auch

gibt die Anzahl der Bits zurück, die das Bitset enthält
(öffentliche Elementfunktion)
(C++20)
zählt die Anzahl der 1 Bits in einer vorzeichenlosen Ganzzahl
(Funktionstemplate)