How to change the value in pairs on cards

I can do:

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

      

But when I do this:

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

      

I got the debugger in VS 2008.

Any hints?

0


a source to share


3 answers


Do you rely on its value? A string literal does not have to have the same address for different purposes (especially when used in different translation units). This way you can create two values:

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

      



Also you don't get any sorting as what happens is that it is sorted by address. Use std::string

one that doesn't have this problem, as it knows about the content and whose operator<

lexicography is comparing:

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

      

+5


a source


View display:

map <char *, int> counter;

      

not a very sane structure because it cannot efficiently manage the char pointers it contains. Change the map to:



map <string, int> counter;

      

and see if that fixes the problem.

+2


a source


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 a key / value pair, if the value is an int value and a value == 1, I somehow couldn't do map [key] -, (because that would do value == 0?)

0


a source







All Articles