Question

Here are the simple code to use db_map. The iterator loop not return key in the order 1, 2, 3... Instead, it returns key like 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;
    }

No correct solution

OTHER TIPS

In this example, it's not clear what kind of database was used to construct the db_map. However, the sequence 256, 1, 257, 2 ... is exactly the sequence I would expect for a memcmp sorted BTree on a little-endian machine.

db_map provides a std::map interface to a Berkeley DB BTree. However, underneath, the key comparison function for db_map is defined by the BTree comparison function.

From the Db::set_bt_compare documentation:

If no comparison function is specified, the keys are compared lexically, with shorter keys collating before longer keys

To the database, a key is nothing more than a sequence of bytes. If no key comparison function is specified, memcmp is used to compare keys. If you want to iterate in the standard numeric order, assign a comparison function using 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;
}

Note that my example uses the four parameter compare function from BDB 6.0. Comparison functions for BDB 5.0 do not include the last parameter. See here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top