【问题标题】:How can I change the value in a pair in maps如何更改地图中的一对值
【发布时间】:2009-05-20 08:01:43
【问题描述】:

我能做到:

map<char*, int> counter;
++counter["apple"];

但是当我这样做时:

--counter["apple"] // when counter["apple"] ==2;

我在 VS 2008 中挂断了调试器。

有什么提示吗?

【问题讨论】:

  • “调试器挂起”是什么意思?请发布一些说明问题的实际可编译代码。

标签: c++ stl maps


【解决方案1】:

你依赖它的价值吗?字符串文字在不同用途中不需要具有相同的地址(尤其是在不同的翻译单元中使用时)。因此,您实际上可以通过以下方式创建两个值:

counter["apple"] = 1;
counter["apple"] = 1;

你也没有得到任何排序,因为发生的是它按地址排序。使用std::string 没有这个问题,因为它知道内容并且其operator&lt; 比较字典:

map<std::string, int> counter;
counter["apple"] = 1;
assert(++counter["apple"] == 2);

【讨论】:

    【解决方案2】:

    表格的地图:

    map <char *, int> counter;
    

    不是一个非常明智的结构,因为它不能有效地管理它包含的 char 指针。将地图更改为:

    map <string, int> counter;
    

    看看能不能解决问题。

    【讨论】:

      【解决方案3】:

      我发现了问题。 如果我将其更改为:

      map<string,int> counter;
      counter["apple"]++;
      
      if(counter["apple"]==1)
         counter.erase("apple");
      else 
         counter["apple"]--; //this will work
      

      在 Key/value 对中,如果 value 是 int 且 value ==1,我不知何故无法执行 map[key]--,(因为这会使 value ==0?)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-24
        • 2011-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多