Spec-Zone.ru › C++

std::bitset<N>::count

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

Возвращает количество битов, установленных в true.

Возвращаемое значение

Количество битов, установленных в true.

Пример

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

Вывод:

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

См. также

size
возвращает количество битов, которые содержит битовый набор
(открытая функция-член)
popcount
(C++20)
подсчитывает количество битов 1 в беззнаковом целом числе
(шаблон функции)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/utility/bitset/count

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API