【问题标题】:Berkeley Db db_map iterator not loop with right orderBerkeley Db db_map 迭代器没有以正确的顺序循环
【发布时间】:2014-02-09 17:36:28
【问题描述】:

这里是使用 db_map 的简单代码。迭代器循环不按 1、2、3 的顺序返回键 ... 相反,它返回 256,1、257,2 之类的键.....

unique_ptr> mp =make_unique>();

    for (int i = 1; i <= 500; i++)
    {
        mp->insert(pair<int, string>(i,"t")); 
    }

    db_map<int, string>::const_iterator it;

    for (it = mp->begin(); it != mp->end(); ++it)
    {
        cout <<it->first<<endl;
    }

【问题讨论】:

    标签: berkeley-db


    【解决方案1】:

    在此示例中,不清楚使用哪种数据库构建db_map。然而,序列 256, 1, 257, 2 ... 正是我期望在 little-endian 机器上对 memcmp 排序的 BTree 的序列。

    db_map 为 Berkeley DB BTree 提供了一个 std::map 接口。但是,在下面,db_map 的键比较函数是由 BTree 比较函数定义的。

    来自Db::set_bt_comparedocumentation

    如果没有指定比较函数,则按词法比较键,较短的键在较长的键之前排序

    对于数据库来说,一个键只不过是一个字节序列。如果未指定键比较函数,则使用memcmp 比较键。如果您想以标准数字顺序进行迭代,请使用 Db::set_bt_compare 分配一个比较函数:

    #include <iostream>
    #include <dbstl_map.h>
    #include <db_cxx.h>
    
    using namespace dbstl;
    
    int key_compare(DB* db, const DBT* a, const DBT* b, size_t* u)
    {
        int i,j;
        if (0 == a->size || 0 == b->size)
        {
            return 0;
        }
        std::memcpy(&i, a->data, sizeof(i));
        std::memcpy(&j, b->data, sizeof(j));
        return i-j;
    }
    
    int main()
    {
        DbEnv* env = new DbEnv(DB_CXX_NO_EXCEPTIONS);
        env->open("/home/centinela", DB_CREATE|DB_INIT_MPOOL, 0);
    
        Db* db = new Db(env, DB_CXX_NO_EXCEPTIONS);
        db->set_bt_compare(&key_compare);
        db->open(NULL, "test.db", NULL, DB_BTREE, DB_CREATE, 0);
    
        typedef dbstl::db_map<int,std::string> map_type;
        map_type* mp = new map_type(db, env);
    
        for (int i = 1; i <= 500; ++i)
        {
            mp->insert(std::pair<int,std::string>(i,"t"));
        }
    
        map_type::const_iterator it;
        for (it = mp->begin(); it != mp->end(); ++it)
        {
            std::cout << it->first << std::endl;
        }
    
        delete db;
        delete env;
    }
    

    请注意,我的示例使用了 BDB 6.0 中的四参数比较功能。 BDB 5.0 的比较函数不包括最后一个参数。见here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多