Bit Array in C++

前端 未结 8 1074
旧时难觅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: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);
    

提交回复
热议问题