BitMap

c++實現的BitMapc++

參考:https://blog.csdn.net/kl1106/article/details/79478787spa

#include<bits/stdc++.h>
using namespace std;
/**
    BitMap
    用於判斷上百億數中,哪一個數重複出現
    用每一位作標誌位
*/
class BitMap{
private:
    //空間首指針
    char* s;
    //能存儲多少個數
    int number;

public:
    //有tempNumber個數
    BitMap(int tempNumber){
        number = tempNumber;
        s = (char *)malloc(sizeof(char) * ((number>>3) + 1));
    }
    void add(int n){
        int index = n >> 3;
        int position = n & 0x07;
        //1<<position 就是對應位爲1 或一下將該位設爲1,表示添加進來
        s[index] |= (1<<position);
    }
    void clear(int n){
        int index = n >> 3;
        int position = n & 0x07;
        //1 <<position 在 ~ 一下,對應位爲0 其餘位爲1,與一下將這位置爲0 表示清除掉
        s[index] &= ~(1<<position);
    }
    bool contains(int n){
        int index = n >> 3;
        int position = n & 0x07;
        //找到對應位,判斷是否是0
        //注意:若是是和1比較,會出錯
        return ((s[index] & (1 << position)) != 0);
    }
};
int main(){
    BitMap tm(10);
    tm.add(2);
    cout << tm.contains(2) << endl;
    tm.clear(2);
    cout << tm.contains(2) << endl;

    return 0;
}
相關文章
相關標籤/搜索