std::bitset<N>::count
ja.cppreference.net より
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'; // 最初の未設定ビットを検索 std::size_t idx = 0; while (idx < b.size() && b.test(idx)) ++idx; // ビットセットの半分が埋まるまでビットを設定 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
関連項目
|
bitsetが保持するビット数を返す
(public member function) |
|
|
(C++20)
|
符号なし整数の
1
ビット数を数える
(function template) |