【发布时间】:2009-05-20 08:01:43
【问题描述】:
我能做到:
map<char*, int> counter;
++counter["apple"];
但是当我这样做时:
--counter["apple"] // when counter["apple"] ==2;
我在 VS 2008 中挂断了调试器。
有什么提示吗?
【问题讨论】:
-
“调试器挂起”是什么意思?请发布一些说明问题的实际可编译代码。
我能做到:
map<char*, int> counter;
++counter["apple"];
但是当我这样做时:
--counter["apple"] // when counter["apple"] ==2;
我在 VS 2008 中挂断了调试器。
有什么提示吗?
【问题讨论】:
你依赖它的价值吗?字符串文字在不同用途中不需要具有相同的地址(尤其是在不同的翻译单元中使用时)。因此,您实际上可以通过以下方式创建两个值:
counter["apple"] = 1;
counter["apple"] = 1;
你也没有得到任何排序,因为发生的是它按地址排序。使用std::string 没有这个问题,因为它知道内容并且其operator< 比较字典:
map<std::string, int> counter;
counter["apple"] = 1;
assert(++counter["apple"] == 2);
【讨论】:
表格的地图:
map <char *, int> counter;
不是一个非常明智的结构,因为它不能有效地管理它包含的 char 指针。将地图更改为:
map <string, int> counter;
看看能不能解决问题。
【讨论】:
我发现了问题。 如果我将其更改为:
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?)
【讨论】: