c – 使用char *作为std :: map中的键,它是如何工作的

前端之家收集整理的这篇文章主要介绍了c – 使用char *作为std :: map中的键,它是如何工作的前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这个问题直接与 using char as a key in stdmap有关.

我理解传入的比较函数的作用以及为什么它需要char *类型作为键.但是,我不确定更新实际上是如何工作的.

我很好奇你要更新密钥的情况. std :: map如何知道如何比较const char *之间的相等性,cmp_str只告诉map将键插入到树中的顺序.

我已经对stl_tree.h代码(pulled from here)进行了一些挖掘,但是找不到多少.我唯一的猜测是它做了直接记忆比较.

我对underling stl_tree类如何处理这种情况感兴趣,或者它是否一直没有正确处理它,什么边缘情况会破坏?

@H_301_12@#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*,cmp_str>::iterator it = map.begin(); for (; it != map.end(); it++ ) { std::cout << (*it).first << ": " << (*it).second << std::endl; } return 0; }

产量

@H_301_12@aa: 1 ba: 7 bb: 6 ca: 2 ea: 3

解决方法

有序容器都使用等价类:如果一个小于另一个,则两个值a和b被认为是等价的:!(a< b)&& !(b< a)或者,如果你坚持用二元谓词表示符号!pred(a,b)&& !pred(b,a). 请注意,您需要将指针保留在地图中:如果指针超出范围,您将得到奇怪的结果.当然,字符串文字在程序的整个生命周期内都保持有效.

猜你在找的C&C++相关文章