您的位置:首页 > 其它

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

2012-12-13 14:34 288 查看
程序设计中经常会出现这样的场景:遍历一个字符串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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐