简体   繁体   中英

what kind of data structure should I use in this case?

I have a function, it is called inside a loop, it can generate a set of integer for each loop, for example:

result for loop 1: {1 1 1 2}
result for loop 2: {1 1 1 3}
result for loop 3: {2 1 1 3}
result for loop 4: {3 1 3 2}

and this function may generate duplication result, for example, result 2 and result 3 is the same. I need to put these results inside a data structure, but can not put the duplication, if the result 2 is the same as result 3, only one of them should be kept, how to achieve it in C ?

If the range of items is small enough, you can use bitmaps as a mean of enumeration. Eg if you want to represent set of integers in range from 1 to 32, all that is required is a 32-bit integer used as a bitmap:

00000001 00000001 00000000 00000000    - for set {8,16}
       ^        ^
       8        16

etc.

If the range is larger, use array of bytes, where each bit represents whether value at this position is present in set:

#define MAXVAL 1024

typedef unsigned char bitmap_t[];
byte bitmap[1 + MAXVAL / CHAR_BIT] = { 0 };
// CHAR_BIT is defined in limit.h and is equal to count of bits in a byte

void insert(bitmap_t bitmap, unsigned val) {
  assert(val < MAXVAL);
  bitmap[val / CHAR_BIT] |= (1 << (val % CHAR_BIT);
}

int is_present(bitmap_t bitmap, unsigned val) {
  assert(val < MAXVAL);
  return bitmap[ val / CHAR_BIT ] & (1 << (val % CHAR_BIT));
}

In C++, this would be easy. Just use a std::set of std::tuple s. In C, you have to implement all the functionality yourself or find a good library, but the overall approach is the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM