std::bitset<N>::count
来自cppreference.com
<tbody>
</tbody>
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 << "初值: " << b << '\n';
// 寻找首个未设置的位
std::size_t idx = 0;
while (idx < b.size() && b.test(idx))
++idx;
// 继续设置位直至 bitset 有一半被填充
while (idx < b.size() && b.count() < b.size() / 2)
{
b.set(idx);
std::cout << "设置位 " << idx << ": " << b << '\n';
while (idx < b.size() && b.test(idx))
++idx;
}
}
输出:
初值: 00010010
设置位 0: 00010011
设置位 2: 00010111
参阅
| 返回位集保有的位数 (公开成员函数) | |
(C++20) |
计量无符号整数中为 1 的位的数量 (函数模板) |