tags:

views:

74

answers:

3

I can do:

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

But when I do:

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

I got debugger hung up in VS 2008.

Any hints?

+5  A: 

Do you rely on the value of it? A string literal is not required to have the same address in different uses of it (especially when used in different translation units). So you may actually create two values by this:

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

Also you get no kind of any sorting, since what happens is that it sorts by address. Use std::string which does not have that problem as it's aware of the content and whose operator< compares lexicographical:

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

A map of the form:

map <char *, int> counter;

is not a very sensible structure, because it cannot manage the char pointers it contains effectively. Change the map to:

map <string, int> counter;

and see if that cures the problem.

anon
A: 

I found the problem. If I change it to:

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

if(counter["apple"]==1)
   counter.erase("apple");
else 
   counter["apple"]--; //this will work

In the Key/value pair, if value is a int and value ==1, I somehow could not do map[key]--, ('cause that will make the value ==0?)