Namespaces
Variants

std:: popcount

From cppreference.net
Utilities library
ヘッダーで定義 <bit>
template < class T >
constexpr int popcount ( T x ) noexcept ;
(C++20以降)

1 ビットの数を x の値で返します。

このオーバーロードは、 T が符号なし整数型(つまり、 unsigned char unsigned short unsigned int unsigned long unsigned long long 、または拡張符号なし整数型)である場合にのみ、オーバーロード解決に参加します。

目次

翻訳の説明: - 「Contents」を「目次」に翻訳しました - HTMLタグ、属性、
タグ内のテキストは翻訳していません
- C++固有の用語(Parameters、Return value、Notes、Example、See also)は原文のまま保持しました
- 書式と構造は完全に保持されています

パラメータ

x - 符号なし整数型の値

戻り値

1 ビットの数(値 x 内)。

注記

名前 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

関連項目

最上位ビットから開始して、連続する 0 ビットの数を数える
(関数テンプレート)
(C++20)
最上位ビットから開始して、連続する 1 ビットの数を数える
(関数テンプレート)
最下位ビットから開始して、連続する 0 ビットの数を数える
(関数テンプレート)
(C++20)
最下位ビットから開始して、連続する 1 ビットの数を数える
(関数テンプレート)
数値が2の整数乗であるかどうかをチェックする
(関数テンプレート)
true に設定されているビットの数を返す
( std::bitset<N> の公開メンバ関数)
すべて、いずれか、またはいずれのビットも true に設定されているかどうかをチェックする
( std::bitset<N> の公開メンバ関数)