Bit Array in C++

前端 未结 8 1064
旧时难觅i
旧时难觅i 2021-02-05 06:09

When working with Project Euler problems I often need large (> 10**7) bit array\'s.

My normal approach is one of:

bool* sieve = new bool[N];

bool sieve[         


        
相关标签:
8条回答
  • 2021-02-05 06:53

    You might be interested in trying the BITSCAN library as an alternative. Recently an extension has been proposed for sparseness, which I am not sure is your case, but might be.

    0 讨论(0)
  • 2021-02-05 06:54

    You can use a byte array and index into that. Index n would be in byte index n/8, bit # n%8. (In case std::bitset is not available for some reason).

    0 讨论(0)
  • 2021-02-05 06:55

    A 'bool' type isn't stored using only 1 bit. From your comment about the size, it seems to use 1 entire byte for each bool.

    A C like way of doing this would be:

    uint8_t sieve[N/8]; //array of N/8 bytes
    

    element of array is:

    result = sieve[index / 8] || (1 << (index % 8)); 
    

    or

    result = sieve[index >> 3] || (1 << (index & 7));
    

    set 1 in array:

    sieve[index >> 3] |= 1 << (index & 7);
    
    0 讨论(0)
  • 2021-02-05 06:57

    For better or for worse, std::vector<bool> will use bits instead of bool's, to save space. So just use std::vector like you should have been in the first place.

    If N is a constant, you can use std::bitset.

    0 讨论(0)
  • 2021-02-05 07:02

    If N is known at compile time, use std::bitset, otherwise use boost::dynamic_bitset.

    0 讨论(0)
  • 2021-02-05 07:04

    A 'bool' type isn't stored using only 1 bit. From your comment about the size, it seems to use 1 entire byte for each bool.

    A C like way of doing this would be:

    uint8_t sieve[N/8]; //array of N/8 bytes
    

    and then logical OR bytes together to get all your bits:

    sieve[0] = 0x01 | 0x02; //this would turn on the first two bits
    

    In that example, 0x01 and 0x02 are hexadecimal numbers that represent bytes.

    0 讨论(0)
提交回复
热议问题