我能做到:
map<char*, int> counter;
++counter["apple"];
但是当我这样做时:
--counter["apple"] // when counter["apple"] ==2;
我在VS 2008中挂了调试器。
任何提示?
答案 0 :(得分:5)
你依靠它的价值吗?字符串文字在不同的使用中不需要具有相同的地址(特别是在不同的翻译单元中使用时)。所以你实际上可以创建两个值:
counter["apple"] = 1;
counter["apple"] = 1;
此外,您没有任何排序,因为会发生的事情是按地址排序。使用没有该问题的std::string
,因为它知道内容并且其operator<
比较词典:
map<std::string, int> counter;
counter["apple"] = 1;
assert(++counter["apple"] == 2);
答案 1 :(得分:2)
表格地图:
map <char *, int> counter;
不是一个非常合理的结构,因为它无法有效地管理它包含的char指针。将地图更改为:
map <string, int> counter;
并查看是否可以解决问题。
答案 2 :(得分:0)
我发现了问题。 如果我将其更改为:
map<string,int> counter;
counter["apple"]++;
if(counter["apple"]==1)
counter.erase("apple");
else
counter["apple"]--; //this will work
在Key / value对中,如果value是一个int且值== 1,我不知道怎么做map [key] - ,('因为那会使值== 0?)