Algorithm learning-bitmap implementation (c ++)
BitMap Introduction
Here, BitMap refers to storing data in a data structure in bit.
Each user has only two values: 0 and 1. If it is 0, it indicates that the value does not exist. If it is 1, it indicates that it exists.
For example:
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
This is 24 bits, that is, 24bit, and 8 bits are 1 byte. The space here is three bytes.
In this case, if we want to store2 4 6 8 9 10 17 19 21These numbers are included in our BitMap. We only need to set the corresponding bit1You can.
[0 0 0 1 0 1 0 1 0 0 0 0 0 1 1 1 0 1 0 1 0 1 0 0 0 0]
In this way, we only store three bytes.9 * sizeof(int)A number in size. In a 64-bit compilerintType is32bitThat is, four bytes. We store so many numbers that we cannot even store an int.
BitMap implementation
In fact, BitMap implementation is not very difficult, but it may not be very difficult to use BitMap operations at ordinary times. So I am not familiar with it.
There are three main operations, except initialization, that isSet (), get (), and del ()Method, one is to set index to 1, and the other is to get the index bit0 or 1Finally, the index position is 0.
The following is code implementation:
//// Header. h // BloomFilter /// Created by Alps on 15/3/19. // Copyright (c) 2015 chen. all rights reserved. //// this is BitMap. h file. Class BitMap {public: BitMap () {bitmap = NULL; size = 0;} BitMap (int size) {// contractor, init the bitmap = NULL; bitmap = new char [size]; if (bitmap = NULL) {printf ("ErroR In BitMap Constractor! \ N ") ;}else {memset (bitmap, 0x0, size * sizeof (char); this-> size = size ;}} /** set the index bit to 1; */int bitmapSet (int index) {int addr = index/8; int addroffset = index % 8; unsigned char temp = 0x1 <addroffset; if (addr> (size + 1) {return 0;} else {bitmap [addr] | = temp; return 1 ;}}/** return if the index in bitmap is 1; */int bitmapGet (int index) {int addr = index/8; int addroffse T = index % 8; unsigned char temp = 0x1 <addroffset; if (addr> (size + 1) {return 0 ;} else {return (bitmap [addr] & temp)> 0? 1: 0;}/** del the index from 1 to 0 */int bitmapDel (int index) {if (bitmapGet (index) = 0) {return 0 ;} int addr = index/8; int addroffset = index % 8; unsigned char temp = 0x1 <addroffset; if (addr> (size + 1) {return 0 ;} else {bitmap [addr] ^ = temp; return 1 ;}} private: char * bitmap; int size ;};
Call methods.
The code is relatively simple. My blog below will write the Bloom Filter and use this BitMap.