Core Module
12 min forge
C++ Bitset
Understanding compact storage and manipulation of bit arrays for high-performance bitwise logic.
C++ Bitset
π What is it
std::bitset is a template class that represents a fixed-size sequence of N bits. It provides a more compact and convenient way to store and manipulate bit arrays compared to raw integers or boolean arrays.
β‘ When to use
Ideal for problems involving bit manipulation, sets of small integers, and high-performance bitwise logic (e.g., subset problems, state representation).
π§ Time complexity
- Access: $O(1)$.
- Bitwise Logic (&, |, ^): $O(N/W)$ where $W$ is word size (usually 32 or 64).
π» Code example
cpp Standard#include <bitset> std::bitset<8> bits(42); // Binary: 00101010 bits.set(0); // Sets first bit: 00101011 std::cout << bits.count(); // Number of set bits std::cout << bits.to_string(); // "00101011"
β Common mistakes
- Fixed Size: Forgetting that
std::bitsetsize must be known at compile-time (usestd::vector<bool>ordynamic_bitsetfor runtime sizing). - Zero-indexing: Bits are indexed from right to left (LSB to MSB), which can be confusing.
- Resource Intensive: Using very large bitsets on the stack can cause stack overflow.