std::bitset::count(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– NAME

okay bestie, welcome to std::bitset::count(3) from the C++ Standard Libary manual β€” yep, that’s the manual name, folded in near the top like a little name tag 🫢. The NAME is literally std::bitset::count - std::bitset::count, and honestly? iconic, concise, no notes πŸ’….

✨ Synopsis ✨

The signature is serving exactly this:

std::size_t count() const;  (noexcept since C++11)
                            (constexpr since C++23)

It returns the number of bits that are set to true. That’s the whole vibe check: count the true bits, periodt πŸ”₯.

πŸŽ€ Parameters

(none) β€” zero parameters, nada, no arguments to hand over. She takes nothing and still delivers πŸ‘‘.

🫢 Return value

Number of bits that are set to true. That’s it, that’s the return value, and it ate πŸ’–.

🎬 Example

bestie, here’s the example code exactly as it appears, no cap:

// Run this code

#include <bitset>
#include <iostream>

int main()
{
    std::bitset<8> b("00010010");
    std::cout << "Initial value: " << b << '\n';

    // Find the first unset bit
    std::size_t idx = 0;
    while (idx < b.size() && b.test(idx))
        ++idx;

    // Continue setting bits until half the bitset is filled
    while (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

expected output, fr fr:

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

πŸ‘€ See also

  • size β€” returns the number of bits that the bitset holds (public member function)
  • popcount β€” counts the number of 1 bits in an unsigned integer (C++20) (function template)

source/version + date sign-off: this page is from http://cppreference.com, dated 2024.06.10, and the page title is std::bitset::count(3). Mwah, bye bestie πŸ’‹πŸŽ€πŸ¦‹

πŸ“¦ where this page comes from