【问题标题】:Custom sort by value using tokyo cabinet in C在 C 中使用 tokyo cabinet 按值自定义排序
【发布时间】:2014-04-04 18:20:47
【问题描述】:

我正在使用 tokyo cabinet 实现一个 btree,但我想知道是否可以对值进行排序。我知道我可以使用tcbdbsetcmpfunc 为键设置自定义比较功能,但不确定值?

我问这个是因为大多数时候我只需要前 1000 条记录,假设我的值已排序。否则我将不得不对数百万条记录进行循环排序并获得前 1000 条记录,这可能会很慢。

例如:

#include <tcutil.h>
#include <tcbdb.h>
#include <stdbool.h>
#include <stdint.h>

struct foo {
    int one;
    double two;
    char *three;
};

// sort by three field
static int val_cmp(const char *aptr, int asiz, const char *bptr, int bsiz, void *op) {
    return 1;
}

int main() {
    int ecode; 
    TCBDB *db;
    db = tcbdbnew();
    struct foo *f;

    tcbdbsetcmpfunc(db, val_cmp, f); // sort by struct->three?

    // open the database
    if(!tcbdbopen(db, "struct.tcb", BDBOWRITER | BDBOCREAT)){
        ecode = tcbdbecode(db);
        fprintf(stderr, "open error: %s\n", tcbdberrmsg(ecode));
    }

    f = malloc(sizeof(struct foo));
    f->one = 100;
    f->two = 1.1111;
    f->three = "Hello World";
    printf("put: %d\n", tcbdbput(db, "foo", 3, f, sizeof(struct foo)));

    f = malloc(sizeof(struct foo));
    f->one = 100;
    f->two = 1.1111;
    f->three = "Hello Planet";
    printf("put: %d\n", tcbdbput(db, "bar", 3, f, sizeof(struct foo)));

    char *key;
    BDBCUR *cursor;
    cursor = tcbdbcurnew(db);
    tcbdbcurfirst(cursor);
    while ((key = tcbdbcurkey2(cursor)) != NULL) {
        struct foo *val;
        int size;
        val = tcbdbcurval(cursor, &size);
        printf("%s: one=%d\n", key, val->one);
        printf("%s: two=%f\n", key, val->two);
        tcbdbcurnext(cursor);
    }
    tcbdbdel(db);
    return 0;
}

【问题讨论】:

    标签: c sorting struct tokyo-cabinet


    【解决方案1】:

    我认为你不能定义值的顺序。

    我建议有第二个 tokyocabinet db,映射 从值到键。我希望通过这种间接方式 你仍然可以得到很好的表现。

    【讨论】:

      【解决方案2】:

      东京内阁没有嵌入排序机制。您可以喜欢使用列表和自定义排序

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 2019-02-28
      • 1970-01-01
      • 2013-05-05
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多