include
define MAX_WORDS 10000
define MAX DocNum 1000
typedef struct {
char *word;
int doc_id;
} KeywordDoc;
typedef struct {
KeywordDoc *entries;
int size;
int capacity;
} InvertedIndex;
void init_index(InvertedIndex *index, int capacity) {
index->entries = malloc(sizeof(KeywordDoc) * capacity);
index->size = 0;
index->capacity = capacity;
}
void add_document(InvertedIndex *index, const char *word, int doc_id) {
for (int i = 0; i < index->size; i++) {
if (strcmp(index->entries[i].word, word) == 0) {
index->entries[i].doc_id = doc_id;
return;
}
}
if (index->size >= index->capacity) {
index->capacity *= 2;
index->entries = realloc(index->entries, sizeof(KeywordDoc) * index->capacity);
}
index->entries[index->size].word = strdup(word);
index->entries[index->size].doc_id = doc_id;
index->size++;
}
int main() {
InvertedIndex index = { NULL, 0, 10};
add_document(&index, "example", 1);
add_document(&index, "example", 2);
// 打印索引内容
for (int i = 0; i < index.size; i++) {
printf("%s -> %d\n", index.entries[i].word, index.entries[i].doc_id);
}
free(index.entries);
return 0;
}
```
五、注意事项
扩展性: