通过bitmap的方式用8个int实现对256个char是否出现过做记录

程序设计中经常会出现这样的场景:遍历一个字符串a(例如:“A dog in on the floor.”),对于字符串b(例如“dnr”)中出现过的字符,统统删掉。

那么对于b中出现的字符,通常可以保存在bool label[256]中来记录某个字符是否在字符串b中。

但是还可以用一种更省内存的方式,就是bitmap。

通过定义Set,ReSet和Get宏来快速定位某一个bit。

并且使用sizeof(int)和动态数组来适应64位平台。

#include <iostream>
using namespace std;

int intWidth = sizeof(int) * 8;
int *label = new int[256/intWidth];

#define Set(i) label[i/intWidth] |= 1<<(i%intWidth)
#define ReSet(i) label[i/intWidth] &= 0<<(i%intWidth)
#define Get(i) (label[i/intWidth] >> (i%intWidth))&0x01

int main()
{
    memset(label, 0, 256/intWidth * sizeof(int));
    for (int i = 0; i < 256; i++)
    {
        unsigned char c = i;
        cout<<"====================================="<<endl;
        cout<<"i = "<<i<<"    c = "<<c<<endl;
        Set(c);
        cout<<"After Set("<<c<<") ";
        if (Get(c))
            cout<<c<<" exists!"<<endl;
        else
            cout<<c<<" not exists!"<<endl;

        ReSet(c);
        cout<<"After ReSet("<<c<<") ";
        if (Get(c))
            cout<<c<<" exists!"<<endl;
        else
            cout<<c<<" not exists!"<<endl;
        cout<<"====================================="<<endl<<endl;
    }

    return 0;
}

 

 

 

 

 

 

EOF

posted on 2012-12-13 14:34  kkmm  阅读(343)  评论(0编辑  收藏  举报