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::bitset size must be known at compile-time (use std::vector<bool> or dynamic_bitset for 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.