位圖法就是bitmap的縮寫。所謂bitmap,就是用每一位來存放某種狀態,適用於大規模數據,但數據狀態又不是很多的情況。通常是用來判斷某個數據存不存在的。在STL中有一個bitset容器,其實就是位圖法。
舉個例子來說明一下:
給40億個不重複的無符號整數,沒排過序。給一個無符號整數,如何快速判斷一個數是否在這40億個數中。
40億個數全部存放大約要用16G的內存空間,這肯定是不現實的,所以我們想着,如何節省內存呢?
應用位圖,需要500M的空間就夠了。如果數字存在,就將對應位圖中的位置1,這時候要去查找一個數字,就直接去位於中的對應位去找就好了。
一個整型有32位,所以個字節能夠表示32個數,這我們用vector來實現位圖:
#pragma once
#include <iostream>
using namespace std;
#include <vector>
class Bitmap
{
public:
Bitmap()
{}
Bitmap(const size_t range)
{
//開空間
_a.resize((range >> 5) + 1, 0);
}
void Set(size_t num)
{
size_t index = num >> 5;//判斷在第幾個整形中
size_t pos = num % 32; // 找到第幾個整形之後,判斷在整形的第幾個位置
_a[index] |= (1 << pos);
}
void Reset(size_t num)
{
size_t index = num >> 5;
size_t pos = num % 5;
_a[index] &= ~(1 << pos);
}
bool Test(size_t num)
{
size_t index = num >> 5;
size_t pos = num % 5;
return _a[index] & (1 << pos);
}
protected:
vector<int> _a;
};
void TestBitmap()
{
Bitset bs(1000);
bs.Set(1);
bs.Set(16);
bs.Set(88);
bs.Reset(1);
}