Bitmap用于数据查询和判重

本文介绍了一种使用位图(bitmap)进行数据处理的方法。利用位图的特性,通过位操作实现高效的数据存储和检索。示例代码展示了如何通过位图去除字符串中的重复字符。

        位图(bitmap)是编码布尔信息的非常简洁的方式,位图的思想是:整数类型(字符类型)的每个位都可以编码一个布尔值——通常用0表示false,用1表示true。通过位操作将其中的某位设置成0或者1。

#include<iostream>
using namespace std;

int main()
{
   int k=1<<6;  //将第6个bit位为1,其余为0
   int j=1<<7;
   int map=4;
   map |=k;  //将map的第6个bit位设置成1;
   bool flag=(map & j); //判断map的第7个bit位是否为1。
   
   //参考网上的一个示例程序: 
   int i;
  char *source = "aaabbccdabgf";  
  
  char *dest;
  char *temp;

  unsigned int bitmap[8] = {0,0,0,0,0,0,0,0};
  unsigned char c;
  unsigned int mask;

  dest = (char*)malloc(strlen(source));
  temp = dest;

  printf("Before %s\n", source); 
  i=0;
  while(source[i])
  {
    c = source[i];
    mask = 1 << (c % 32); //1左移若干位,一个整型数据一般为32bit 
    if ((bitmap[c/32] & mask) == 0)   
    {
      *temp++ = source[i];
      bitmap[c/32] |= mask; //设置bit位为1 
    }
    i++;
  }
  *temp = '\0'; 
    
  printf("After %s\n", dest);
}

相关文献:

 http://blog.youkuaiyun.com/yushuai007008/article/details/7466945

http://bbs.chinaunix.net/thread-3558006-1-1.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值