【发布时间】:2012-10-15 18:23:38
【问题描述】:
此问题与using char as a key in stdmap 直接相关。
我了解传入的比较函数的作用以及为什么需要将 char * 类型作为键。但是,我不确定更新实际上是如何工作的。
我很好奇您正在更新密钥的情况。 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
【问题讨论】:
-
我确实认为这是一个 memcmp 类型的操作。
-
您有什么特别的理由不只使用
std::string作为键吗? -
我的教授写了上面的
cmp_str函数,我提出了这个问题,他没有回答这个问题。我进行了一些测试,但未能遇到边缘情况,但我仍然对它的工作原理感到困惑,因为我认为它只会在表格中插入另一个条目。 -
基本上,如果 cmpstr 在两个方向上都返回 false,它就知道键是相等的。
标签: c++ map stdmap const-char