用位图解决大数据存储

来源:互联网 发布:禁毒网络知识竞赛答案 编辑:程序博客网 时间:2024/05/01 15:24

这里写图片描述
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;}
1 0
原创粉丝点击