位图法就是bitmap的缩写。关于bitmap,就是用每一位来存放某种状态,适用于大规模数据,但数据状态又不是很多的情况。
通常是用来判断某个数据存不存在的。
位图的优缺点:
优点:
(1),是速度快,内存空间占用小,能表示大范围的数据。
缺点:
(2),可读性差 (3),位图存储的元素个数虽然比一般做法多,但是存储的元素大小受限于存储空间的大小。 (4),位图对有符号类型数据的存储,需要 2 位来表示一个有符号元素。这会让位图能存储的元素个数,元素值大小上限减半。
位图的实现:
#include<iostream> using namespace std; #include<vector> class BieSet { public: BieSet(size_t rang) { _a.resize((rang >> 5) + 1); } 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 % 32; _a[index] &= ~(1 << pos); } bool Test(size_t num) { size_t index = num >> 5; size_t pos = num % 32; return _a[index] & (1 << pos); } protected: vector<int> _a; }; void BitSetTest() { BieSet b(1000); b.Set(1); b.Set(33); } int main() { BitSetTest(); system("pause"); return 0; }