繁体   English   中英

使用C中的东京橱柜按值自定义排序

[英]Custom sort by value using tokyo cabinet in C

我正在使用东京内阁实现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;
}

我认为您无法定义值的顺序。

我建议再创建一个tokyocabinet数据库,从值到键的映射。 我希望通过这种间接方式仍然可以获得不错的性能。

东京内阁没有嵌入分类机制。 您可以使用列表及其自定义排序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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