public member function
<bitset>

std::bitset::count

size_t count() const;
size_t count() const noexcept;
Count bits set
Returns the number of bits in the bitset that are set (i.e., that have a value of one).

For the total number of bits in the bitset (including both zeros and ones), see bitset::size.

Parameters

none

Return value

The number of bits set.

size_t is an unsigned integral type.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// bitset::count
#include <iostream>       // std::cout
#include <string>         // std::string
#include <bitset>         // std::bitset

int main ()
{
  std::bitset<8> foo (std::string("10110011"));

  std::cout << foo << " has ";
  std::cout << foo.count() << " ones and ";
  std::cout << (foo.size()-foo.count()) << " zeros.\n";

  return 0;
}

Output:

10110011 has 5 ones and 3 zeros.


Data races

The bitset is accessed.

Exception safety

Strong guarantee: if an exception is thrown, there are no changes in the bitset.
If the bitset size is too big to be represented by the return type, overflow_error is thrown.

See also