这个问题直接关系到using char as a key in stdmap .
我了解传入的比较函数的作用以及为什么 char *
类型需要它作为键。但是,我不确定更新的实际工作方式。
我很好奇您更新 key 的情况。 std::map
如何知道如何比较 const char *
之间的相等性,cmp_str
只告诉 map 插入键的顺序那个树。
我已经深入研究了 STL_tree.h
代码 ( pulled from here ),但没有找到太多。我唯一的猜测是它在进行直接内存比较。
我对底层 STL_tree
类如何处理这种情况很感兴趣,或者如果它不能始终正确处理,会出现什么边缘情况?
代码
#include <map>
#include <iostream>
#include <cstring>
struct cmp_str
{
bool operator()(char const *a, char const *b)
{
return std::strcmp(a, b) < 0;
}
};
int main ( int argc, char ** argv )
{
std::map<const char*, int, cmp_str> map;
map["aa"] = 1;
map["ca"] = 2;
map["ea"] = 3;
map["ba"] = 4;
map["ba"] = 5;
map["bb"] = 6;
map["ba"] = 7;
std::map<const char*, int, cmp_str>::iterator it = map.begin();
for (; it != map.end(); it++ )
{
std::cout << (*it).first << ": " << (*it).second << std::endl;
}
return 0;
}
输出
aa: 1
ba: 7
bb: 6
ca: 2
ea: 3
最佳答案
有序容器都使用等价类:两个值a
和 b
如果一个都不小于另一个,则被认为是等效的:!(a < b) && !(b < a)
或者,如果您坚持使用二元谓词表示法 !pred(a, b) && !pred(b, a)
.
请注意,您需要让指针在您的 map 中保持事件状态:如果指针超出范围,您将得到奇怪的结果。当然,字符串文字在程序的整个生命周期内都保持有效。
关于c++ - 在 std::map 中使用 char* 作为键,它是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12901687/