std::bitset<N>::count
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) |