【问题标题】:Using char* as a key in std::map, how does it work使用 char* 作为 std::map 中的键,它是如何工作的
【发布时间】: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


【解决方案1】:

有序容器都使用等价类:如果两个值 a 和 b 都不小于另一个,则认为这两个值是等价的:!(a &lt; b) &amp;&amp; !(b &lt; a) 或者,如果您坚持使用二进制谓词 !pred(a, b) &amp;&amp; !pred(b, a) 的表示法.

请注意,您需要将指针保留在地图中:如果指针超出范围,您会得到奇怪的结果。当然,字符串文字在程序的整个生命周期内都保持有效。

【讨论】:

    【解决方案2】:

    好吧,cmp_str 可用于查找相同的键。如果cmp_str::operator(x,y) 和cmp_str::operator(y,x) 都返回false,则您找到了重复的密钥。真的没有更多的了。

    【讨论】:

      猜你喜欢
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      • 2012-10-04
      • 2014-08-06
      • 1970-01-01
      • 2011-09-06
      相关资源
      最近更新 更多