用位圖解決大數據存儲

這裏寫圖片描述
BitSet.h

#include<iostream>
#include<assert.h>
using namespace std;

class BitSet
{
public:
    BitSet(size_t N) //N表示存儲數據的範圍
    {
        _size = N / 32 + 1;
        _arr = new size_t[_size];
        memset(_arr, 0, sizeof(size_t)*_size);//給_arr數組初始化全部爲0
    }
    ~BitSet()
    {
        if (_arr)
        {
            delete[] _arr;
        }
    }
    void Set(size_t num)
    {
        int index = num / 32;//index表示數據存儲在數組的第幾個位置
        assert(index < _size);
        int pos = num % 32; //pos表示數組下標爲index的某一位
        _arr[index] |= 1 << (32 - pos);
    }
    void Reset(size_t num)
    {
        int index = num / 32;
        assert(index < _size);
        int pos = num % 32;
        _arr[index] &= ~(1 << (32 - pos));
    }
    void Clear()
    {
        memset(_arr, 0, sizeof(size_t)*_size);
    }
    bool Test(size_t num)//測試num是否已經存在
    {
        int index = num / 32;
        assert(index < _size);
        int pos = num % 32;
        if ((_arr[index] & 1 << (32-pos)) > 0)
        {
            return true;
        }
        return false;
    }
private:
    size_t* _arr;
    size_t _size;
};

main.cpp

#include"BitSet.h"

void Test()
{
    BitSet bt(-1); //將-1強轉成4294967295
    bt.Set(32);
    bt.Set(99);
    bt.Reset(32);
    bt.Test(32);
    //bt.Clear();
    bt.Test(99);
    bt.Test(1);
}
int main()
{
    Test();
    getchar();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章