替换类似STL的映射中的值
replacing values in an STL-like map
我对映射的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;
}
};
相关文章:
- C++:在子类中扩展静态 STL 容器/映射成员?
- 使用无序映射在STL中存储键值对
- STL映射比较器能否以某种方式获取指向映射本身的指针?
- 在 c++ stl 映射中,删除具有重复值的条目
- C++ STL 映射同时更新所有值
- 遍历 STL 映射(集/多集)的最佳方法,同时元素可能会在循环期间被删除并重新插入?
- 如何通过键和值以及在C 中的结果映射中比较两个地图?我们有任何STL API吗?
- 无法将元素添加到 STL 映射
- 为什么不能在STL映射中插入值
- 在 stl 映射和列表 (c++) 上进行迭代的泛型循环
- 未签名的char数组到stl ::映射或其他容器中的键
- 整数和元组的静态 STL 映射返回 0
- C++ STL 比较映射找不到(运算符==)
- 指向类的指针的 STL 映射的 SWIG 类型图
- 将 STL 映射存储到 Boost ConstBufferSequence 中
- 如何在下一次函数调用中使用 STL 映射擦除从最后一个位置
- 如何使用密钥 2 更新 STL 映射键 1 并将值复制到键 2 中
- 为什么当代码尝试在 STL 映射中查找键时出现分段错误
- 快速插入STL映射
- 在C++中,如何在映射STL中插入键作为类