std::bitset<N>::count
From cppreference.com
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ビットの数を数える (関数テンプレート) |