std::popcount
来自 cppreference.cn
定义于头文件 <bit> |
||
template< class T > constexpr int popcount( T x ) noexcept; |
(since C++20) | |
返回 x 的值中为 1 的位的数量。
当且仅当 T
是无符号整数类型时(即,unsigned char、unsigned short、unsigned int、unsigned long、unsigned long long 或扩展无符号整数类型),此重载参与重载决议。
内容 |
[编辑] 参数
x | - | 无符号整数类型的值 |
[编辑] 返回值
x 的值中 1 位的数量。
[编辑] 注解
名称 popcount
是 "population count" 的缩写。
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__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> 的公共成员函数) |