std::bitset<N>::count
来自 zh.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 持有的比特位数
(公开成员函数) |
|
|
(C++20)
|
计算无符号整数中
1
比特的数量
(函数模板) |