Search code examples
c++time-complexitybitsetstd-bitset

What is the complexity of C++ bitset constructor that converts from long?


My guess is O(n) where n is the no. of bits. Or is it constant w.r.t. n? I mean it shouldn’t it just be able to copy the bits from memory?


Solution

  • Mathematically speaking, long has a fixed length, therefore copying it's contents is constant-time operation. On the other hand, you need to zero-out the rest of the bits in the bitset and that you are not able to do in less-than-linear time with respect to the length of the bit_set. So, In theory you cannot do better than O(n), where n is the length of the bitset.

    I guess that from the asymptotical complexity point of view you can safely assume that the complexity of the constructor is the same as zeroing-out the allocated memory.

    This analysis however has some value only for huge values of n and it does not make much sense to me to use a long constructor to initialize a bitset of million bits. So, if the size of the bitset is on the same scale as the size of long, it is practically constant-time.