替换类似STL的映射中的值

replacing values in an STL-like map

本文关键字:映射 STL 替换      更新时间:2023-10-16

我对映射的btree实现有问题(从这里开始)。我的代码如下:

Tree *bt = create_btree();
unsigned char *test = (unsigned char *) malloc(5);
unsigned char *test2 = (unsigned char *) malloc(5);
memset(test, 0, 5);
memset(test2, 0, 5);
memcpy(test + 0, "a", 2);
memcpy(test + 2, "HAM", 3);
memcpy(test2 + 0, "a", 2);
memcpy(test2 + 2, "FRA", 3);
(*bt)[test] = 659;
(*bt)[test2] = 999;
(*bt)[test] = 350;
int value;
unsigned char *key;
Tree::iterator iter;
for (iter = bt->begin(); iter != bt->end(); iter++) {
    key = iter->first;
    value = iter->second;
    printf("Key: ");
    register int i;
    for (i = 0; i < 5; i++)
        printf("%02x ", (int) key[i]);
    printf("; Value: %dn", value);
}
CPPUNIT_ASSERT_EQUAL(2, (int )bt->size());
Tree::iterator it = bt->find(test);
value = (*it).second;
CPPUNIT_ASSERT_EQUAL(350, value);

正如最后一行代码所示,我预计value为350,因为我将test的值从659更改为350。此外,地图内应该只有两个元素,但输出如下:

Key: 61 00 48 41 4d ; Value: 659
Key: 61 00 46 52 41 ; Value: 999
Key: 61 00 48 41 4d ; Value: 350

我给树传递了一个自己实现的比较函数来对元素进行排序:

struct cmpBinary {
    bool operator()(unsigned char *a, unsigned char *b) const {
        //d_size is 5
        bool cmp = memcmp(a, b, d_size);
        return cmp;
    }
};
/* TYPEDEF */
typedef btree::btree_map<unsigned char*, int, cmpBinary, allocator<unsigned char*>, node_size> Tree;

我的问题是,为什么第一个元素数据不会被值350取代?一个有趣的事实是,如果我删除行(*bt)[test2] = 999;,并在第一个元素后面直接插入"第三个"(现在是第二个)元素,那么输出是预期的。

Key: 61 00 48 41 4d ; Value: 350

提前谢谢。

memcmp在内存区域相等的情况下返回0,否则如果第一个内存区域较小则返回负值,如果第二个内存区域较大则返回正值。当我们检查树图的模板定义时,我们会看到:

template <typename Key, typename Value,
          typename Compare = std::less<Key>,
          typename Alloc = std::allocator<std::pair<const Key, Value> >,
          int TargetNodeSize = 256>

因此,我们必须提供自己的std::less版本,并定义低于的含义:

struct cmpBinary {
    inline bool operator()(unsigned char *a, unsigned char *b) const {
        return memcmp(a, b, d_size) < 0;
    }
};