如何更改地图中对中的值

0 c++ maps stl

我可以:

map<char*, int> counter;
++counter["apple"];
Run Code Online (Sandbox Code Playgroud)

但当我这样做时:

--counter["apple"] // when counter["apple"] ==2;
Run Code Online (Sandbox Code Playgroud)

我在VS 2008中挂了调试器.

任何提示?

Joh*_*itb 5

你依靠它的价值吗?字符串文字在不同的使用中不需要具有相同的地址(特别是在不同的翻译单元中使用时).所以你实际上可以创建两个值:

counter["apple"] = 1;
counter["apple"] = 1;
Run Code Online (Sandbox Code Playgroud)

你也得不到任何排序,因为它会按地址排序.使用std::string没有那个问题,因为它知道内容和谁的operator<比较词典:

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