位图

给40亿个不重复的无符号整数,没排过序。给一个无符号整数,如何快速判断一个数是否在这40亿个数中。

40亿个无符号整数加载在内存中大约占空间 4G,但用位图,如果内存够的话,40亿个整型使用位图存储需要500M左右的空间

位图结构:一个数组的每一个二进制位表示一个数据,0表示数据不存在,1表示数据存在。

#include<vector>
#include<iostream>
using namespace std;
class BitMap
{
protected:
    vector<size_t>_array;
    size_t _size;
public:
    BitMap(size_t size)//分配空间
        :_size(0)
    {
        _array.resize((size >> 5) + 1);

} void Set(size_t num)//置1 { size_t index = num >> 5; size_t n = num % 32; _array[index] |= (1 << n); ++_size; } void Reset(size_t num)//置0 { size_t index = num >> 5; size_t n = num % 32; _array[index] &= (~(1 << n)); --_size; } bool Test(size_t num)//是否存在 { size_t index = num >> 5; size_t n = num % 32; return _array[index] & (1 << n); } void clear() { _array.assign(_array.size(), 0); } };

 void TestBit()

{

 if (!in)
 {
  cerr << "some errors happened";
  return;
 }

 string str;
 while (getline(in, str))
 {
     bm.Set(atoi(str.c_str()));//atoi(char *str),用途是将字符串转换成一个整数值,
                            //c_str()将string对象,转化为char*对象
 }
   cout << bm.Test(7) << endl;
   cout << bm.Test(5854) << endl;
}




原文地址:https://www.cnblogs.com/Blog-day/p/My_Blog_Days_21.html