位示图的实现
1. 定义:
位示图(bitmap)又叫位图,它的最小单元是一个bit。每个bit有两种取值1或0。
位示图是一种非常常用的结构,在索引,数据压缩等方面有广泛应用。本文介绍了位图的实现方法及其应用场景。
2. 实现
在C/C++中没有位示图这种数据类型,下面我们利用int来实现一个位示图类
每个int有sizeof(int)*8个bit
3.代码
1: #include<cassert>2: #include<iostream>3:4: using namespace std ;5:6: #define INT_BIT sizeof(int)7: #define MAX 1024*1024*10248: #define SHIFT 59: #define UNIT INT_BIT << 3 // INT_BIT * 2^3
10: #define MASK 0x1f11:12: class BitSet
13: {14: public :
15: BitSet(int maxSize=MAX)
16: : _msize(maxSize)17: {18: pBitset = new int[_msize/UNIT+1] ;19: }20:21: ~BitSet()22: {23: if (pBitset){
24: delete [] pBitset ;
25: }26: }27:28: void set(int i)29: {30: assert(i<_msize) ;31: // i >> SHIFT = i / (2^5)
32: // i & MASK = i % 32
33: int j = i ;
34: if (j>UNIT){
35: j >>= SHIFT ;36: }37: pBitset[j] |= 1 << (i & MASK) ;38: }39:40: void clear(int i)41: {42: assert(i<_msize) ;43: int j = i ;
44: if (j>UNIT){
45: j >>= SHIFT ;46: }47: pBitset[j] &= ~(1 << (i & MASK)) ;48: }49:50: bool test(int i)51: {52: assert(i<_msize) ;53: int j = i ;
54: if (j>UNIT){
55: j >>= SHIFT ;56: }57: return (pBitset[j] & (1<< (i & MASK))) ;
58: }59: private:
60: int _msize ;
61: int *pBitset ;
62: } ;63:
4. 测试代码
1: int main()
2: {3: BitSet bitset(100) ;4: int i = 80 ;
5: bitset.set(i) ;6:7: if (bitset.test(i)){
8: cout << "the pos " << i << " is seted" << endl ;9: }else{
10: cout << "the pos " << i << " is not seted" << endl ;11: }12:13: bitset.clear(i) ;14:15: if (bitset.test(i)){
16: cout << "the pos " << i << " is seted" << endl ;17: }else{
18: cout << "the pos " << i << " is not seted" << endl ;19: }20: }