用位图解决大数据存储

这里写图片描述
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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值