std::popcount
來自 cppreference.com
定義於標頭檔案 <bit> |
||
template< class T > constexpr int popcount( T x ) noexcept; |
(C++20 起) | |
返回 x 值中 1 位元的數量。
此過載僅在 T
為無符號整型(即 unsigned char、unsigned short、unsigned int、unsigned long、unsigned 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> 的公共成員函式) |