名前空間
変種
操作

std::bitset<N>::count

From cppreference.com
< cpp‎ | utility‎ | bitset
 
 
ユーティリティライブラリ
言語サポート
型のサポート (基本型、RTTI)
ライブラリ機能検査マクロ (C++20)
プログラムユーティリティ
可変引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)  
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
 
 
std::size_t count() const;
(C++11 以降 noexcept)
(C++23 以降 constexpr)

セットされている(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

[編集] 関連項目

ビットセットが保持するビットの数を返します。
(public member function) [編集]
(C++20)
符号なし整数内の1ビットの数を数える
(関数テンプレート) [編集]
English 日本語 中文(简体) 中文(繁體)