Set retrieval: bitmap Method
Bitmap Method
Bitmap is a method that describes a set logically.
For example, if the set S is {2, 4, 1, 5, 12}, it is described as 0110 1100 0000 1000 in a bitmap. Two bytes can be used to describe S, and the left side is the low-level bit. If you use bitset <16> for storage, {[15], [14],... [1], [0] }={ 0001000000110110 }.
After describing a set with bitmap, it is easy to perform set operations, such as intersection, sum, and difference.
The following describes the specific operations.
Set S = {1, 2, 4, 5}, set T = {2, 5, 8, 10}
The bitmap of the Set S is 0110110000000000.
The bitmap of the set T is 0010010010100000.
The intersection of S and T is S & T = 0010010000000000 =}
Returns the Union of S and T, that is, S | T = 0110110010100000 =}
Calculate the difference set between S and T, that is, S &~ T = (0110110000000000) & (1101101101011111) = 0100100000000000 =}
The complete code for the above example is as follows:
# Include
# Include
Using namespace std; int main () {cout <"------ bitmap method --- by David ---" <endl; int S [] = {1, 2, 4, 5 }; int T [] = {2, 5, 8, 10}; bitset <16> s, t; s. reset (); t. reset (); int size_s, size_t, I; size_s = sizeof (S)/sizeof (int); size_t = sizeof (T)/sizeof (int ); cout <"set S" <endl; for (I = 0; I <size_s; I ++) {cout <S [I] <"; s. set (S [I]);} cout <endl; cout <"set T" <endl; for (I = 0; I <size_t; I ++) {cout <T [I] <"; t. set (T [I]);} cout <endl; // calculates the intersection bitset <16> r1 (s. to_ulong () & t. to_ulong (); // returns the Union bitset <16> r2 (s. to_ulong () | t. to_ulong (); // returns the bitset of the difference set <16> r3 (s. to_ulong ()&(~ T. to_ulong (); cout <"intersection" <endl; for (I = 0; I <16; I ++) if (r1 [I]) cout <I <"; cout <endl; cout <" union "<endl; for (I = 0; I <16; I ++) if (r2 [I]) cout <I <"; cout <endl; cout <" difference set "<endl; for (I = 0; I <16; I ++) if (r3 [I]) cout <I <""; cout <endl; system ("pause"); return 0 ;}
Run
Column directory
Data Structure and algorithm c pointer