wiki:hpp-bitset
<bitset>
<bitset> is a fixed-size bitfield: each bit is independently addressable and can be set, cleared, or tested. It's more memory-efficient than std::vector<bool> for large fixed-size bit arrays.
Use it for flags, masks, or when you need to track individual bits of a large quantity—like tracking active threads in a thread pool or implementing a sparse boolean matrix.
Example
This example sets and manipulates individual bits in an 8-bit set, checking values, counting set bits, and flipping bits.
// compile: g++ -std=c++11 -o bitsetexample bitsetexample.cpp // run: ./bitsetexample // description: flag management with bitset #include <bitset> #include <iostream> int main() { std::bitset<8> flags; flags.set(2); flags.set(5); std::cout << "bitset: " << flags << "\n"; std::cout << "bit 2 is set: " << flags[2] << "\n"; std::cout << "count of set bits: " << flags.count() << "\n"; flags.flip(2); std::cout << "after flip(2): " << flags << "\n"; return 0; }
wiki/hpp-bitset.md · Last modified: by 127.0.0.1
