您的位置:首页 > 大数据

用位图解决大数据存储

2015-12-05 17:21 148 查看


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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: