Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::bitset<N>::count

      From cppreference.com
      <cpp‎ |utility‎ |bitset
       
       
      Utilities library
       
       
      std::size_t count()const;
      (noexcept since C++11)
      (constexpr since C++23)

      Returns the number of bits that are set totrue.

      [edit]Return value

      Number of bits that are set totrue.

      [edit]Example

      Run this code
      #include <bitset>#include <iostream> constexprauto 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<<"Initial value: "<< b<<'\n'; // Find the first unset bitstd::size_t idx=0;while(idx< b.size()&& b.test(idx))++idx; // Continue setting bits until half the bitset is filledwhile(idx< b.size()&& b.count()< b.size()/2){        b.set(idx);std::cout<<"Setting bit "<< idx<<": "<< b<<'\n';while(idx< b.size()&& b.test(idx))++idx;}}

      Output:

      Initial value: 00010010Setting bit 0: 00010011Setting bit 2: 00010111

      [edit]See also

      returns the number of bits that the bitset holds
      (public member function)[edit]
      (C++20)
      counts the number of1 bits in an unsigned integer
      (function template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/bitset/count&oldid=181099"

      [8]ページ先頭

      ©2009-2025 Movatter.jp