位图 BitMap

来源:互联网 发布:php跳转id代码 编辑:程序博客网 时间:2024/06/05 17:14

看到这个名字就可以想象到位图顾名思义就是通过一个位来存储一个整型,用0和1来标记这个数存在还是不存在。

通常位图可以在内存不够、只判断数字在不在的情况下使用,节省空间。

#pragma once#include <iostream>using namespace std;#include <vector>class BitSet{public:    BitSet(const size_t& range)//range数据的范围    {        size_t n = (range / 32 + 1);//需要开数组大小        _bs.resize(n);//开空间,并完成初始化    }    void Set(const size_t& num)    {        size_t index = num / 32;//表示num在第几个数        size_t pos = num % 32;//表示在那个位        //将num对应位置为1        _bs[index] |= (1<<(31-pos));    }    void ReSet(const size_t& num)    {        size_t index = num / 32;//表示num在第几个数        size_t pos = num % 32;//表示在那个位        //将num对应位置为1        _bs[index] &= ~(1 << (31 - pos));    }    bool Test(const size_t& num)    {        size_t index = num / 32;        size_t pos = num % 32;        size_t tags = _bs[index] & (1 << (31 - pos));        if (tags)            return true;        return false;    }protected:    vector<int> _bs;};//测试函数void TestBitSet(){    BitSet bs(50);    bs.Set(0);    bs.Set(1);    bs.Set(32);    bs.Set(33);    cout << "0?:" << bs.Test(0) << endl;    cout << "1?:" << bs.Test(1) << endl;    cout << "32?:" << bs.Test(32) << endl;    cout << "33?:" << bs.Test(33) << endl;    cout << "35?:" << bs.Test(35) << endl;    bs.ReSet(33);    cout << "33?:" << bs.Test(33) << endl;}
0 0