简体   繁体   English

C ++ STL-Map排序功能

[英]C++ STL-Map sort function

I'm trying to insert binary data into a B-Tree, implementing the STL interface. 我正在尝试将二进制数据插入B树中,以实现STL接口。 My typedefinition is the following: 我的类型定义如下:

typedef btree::btree_map<unsigned char*, int, less<unsigned char*>, allocator<unsigned char*>, node_size> Tree;

The problem is that less<unsigned char*> do not compare the elements as I expect. 问题是less<unsigned char*>不能像我期望的那样比较元素。

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);

cout << "Is equal: " << memcmp(test, test2, 5) << "\n";

memcpy(test + 0, "a\0", 2);
memcpy(test + 2, "HAM", 3);

memcpy(test2 + 0, "a\0", 2);
memcpy(test2 + 2, "HAM", 3);

bt->insert(make_pair(test, 1));
bt->insert(make_pair(test2, 2));

cout << "Is equal: " << memcmp(test, test2, 5) << "\n";


Tree::iterator iter;

for (iter = bt->begin(); iter != bt->end(); iter++) {

    cout << "Data: " << iter->first << " = " << iter->second << "\n";
}

When I run the code snippet above the function memcmp will return 0 which signals that both arrays are equal but the output of the programm is : 当我运行函数memcmp上方的代码片段时,将返回0,这表明两个数组相等,但programm的输出为:

Is equal: 0
Is equal: 0
Data: a = 1
Data: a = 2

I would expect that the second insert would overwrite the first, and only one line with Data: a = 2 will be printed. 我希望第二个插入内容将覆盖第一个插入内容,并且仅打印Data: a = 2一行。 I know that the key will be only printed till '\\0' occurs. 我知道只有在出现'\\ 0'时才会打印密钥。 So here is the key in hex representation: `61 00 48 41 4d'. 因此,这是十六进制表示形式的关键:“ 61 00 48 41 4d”。

Correct me if I'm wrong but I think it has something to do with the less operator. 如果我错了,请纠正我,但我认为这与less运算符有关。

My question is: Is there a way to pass a function like memcmp to the map in order to compare the binary arrays correct. 我的问题是:有没有办法将像memcmp这样的函数传递给映射,以便比较二进制数组是否正确。

Thank in advance 预先感谢

I think it has something to do with the less operator. 我认为这与较少的运算符有关。

Correct. 正确。 less<T*> function will compare pointers, not the content of array that might be pointed by them. less<T*>函数将比较指针,而不是指针可能指向的数组的内容。

Is there a way to pass a function like memcmp to the map in order to compare the binary arrays correct. 有没有一种方法可以将像memcmp这样的函数传递给映射,以便比较二进制数组是否正确。

Yes, see the third template parameter and the first constructor parameter. 是的,请参阅第三个模板参数和第一个构造函数参数。 You can pass a functor of your own choice (assuming btree::btree_map has the same interface as the std::map ). 您可以传递自己选择的函子(假设btree::btree_mapstd::map具有相同的接口)。

I would recommend using a std::vector or std::string as the key instead of a pointer. 我建议使用std::vectorstd::string作为键而不是指针。 Not only do they work with less<> , but you also don't need to manage their memory. 它们不仅可以使用less<> ,而且您也不需要管理它们的内存。

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

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