Wednesday 25 July 2012

bitset Library

<bitset>


A bitset<N> is like a vector<bool> with fixed size N, but without iterators, and supporting logical operators like an N-bit int. Its elements have the values 0 or 1. It is implemented efficiently, with 8 elements per byte. bitset<N> b; // N-bit bitset, N must be a compile time constant
bitset<N> b=x; // Initialize b[0]..b[31] from bits of long x
b[i] // i'th bit, 0 <= i < N or throw out_of_range()
b.size() // N, cannot be changed
b.set(i) // b[i] = 1
b.reset(i) // b[i] = 0
b.flip(i) // b[i] = 1 - b[i]
b.test(i) // true if b[i] == 1
b.set() // Set all bits, also b.reset(), b.flip()
b & b2 // Bitwise AND, also | ^ ~ << >> &= |= ^= <<= >>= == !=
b.count() // Number of bits set to 1
b.any() // true if b.count() > 0
b.none() // true if b.count() == 0
cin >> b // Read bits as '0' and '1' e.g. "10101"
cout << b // Write bits as '0' and '1'
bitset<N> b(s); // Initialize from string s of '0' and '1' or throw invalid_argument()
s=b.template to_string<char>() // Convert to string
x=b.to_ulong() // Convert to unsigned long, throw overflow_error() if bits > 31 set

No comments:

Post a Comment