std::popcount
来自 zh.cppreference.net
| 定义于头文件 <bit>
|
||
template< class T >
constexpr int popcount( T x ) noexcept;
|
(C++20起) | |
返回 11x位的数量,在值 x。
仅当 TT 是无符号整数类型(即 unsigned charunsigned char, unsigned shortunsigned short, unsigned intunsigned int, unsigned longunsigned long, unsigned long longunsigned long long, 或扩展无符号整数类型)。
参数
| x | - | 无符号整数类型的值 |
返回值
值 x 中 1 比特的数量。
注释
名称
popcount
是“population count”的缩写。
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__cpp_lib_bitops
|
201907L
|
(C++20) | 位操作 |
示例
运行此代码
#include <bit> #include <bitset> #include <cstdint> #include <iostream> static_assert(std::popcount(0xFULL) == 4); int main() { for (const std::uint8_t x : {0, 0b00011101, 0b11111111}) std::cout << "popcount( " << std::bitset<8>(x) << " ) = " << std::popcount(x) << '\n'; }
输出:
popcount( 00000000 ) = 0 popcount( 00011101 ) = 4 popcount( 11111111 ) = 8
另见
(C++20) |
计算连续的 0 位的数量,从最高有效位开始 (函数模板) |
(C++20) |
计算连续的 1 位的数量,从最高有效位开始 (函数模板) |
(C++20) |
计算连续的 0 位的数量,从最低有效位开始 (函数模板) |
(C++20) |
计算连续的 1 位的数量,从最低有效位开始 (函数模板) |
(C++20) |
检查一个数是否为 2 的整数次幂(函数模板) |
返回被设置为 true 的位的个数( std::bitset<N> 的公有成员函数)
| |
检查是否全部、任一或没有位被设置为 true ( std::bitset<N> 的公有成员函数)
|