2005年12月30日

Bug on Map

Map a nice container of C++. I love it. But this afternoon, after debugged four hours, I found that there was a bug in my mind about using map.

There was a sample code:
------------------------------------
#include <map>
#include <string>

using namespace std;

int main()
{
map mapTest;
mapTest["Good"] = 2;
mapTest["Morning"] = 3;
mapTest["To"] = 4;
mapTest["You"] = 5;

return 1;
}
------------------------------------
In the above program, before returning, the map content is:
=======Content of mapTest=======
Good 2
Morning 3
To 4
You 5


Then I used a search on this map by "YYThanks" as index, as following:
------------------------------------
#include
#include

using namespace std;

int main()
{
map mapTest;
mapTest["Good"] = 2;
mapTest["Morning"] = 3;
mapTest["To"] = 4;
mapTest["You"] = 5;

int number = mapTest["YYThanks"];

return 1;
}
------------------------------------
Before returning, the content of maptest is:
=======Content of mapTest=======
Good 2
Morning 3
To 4
YYThanks 0
You 5

So, it meant that after the search of "YYThanks", the content of the map is changed. Why it happens? After the discussion with a member of our lab, our conclusion is after the empty query on mapTest, mapTest had a index-value match as "YYThanks"-"0". After changing the value from int to string, I ran such program again, the new match was "YYThanks"-"". It meant that the new match index-value had the default value of the definition kind of value.

It was a deep hiding bug in my program. Luckily, I had found out and debugged it.

There were two another kind of searching on map in C++ Primer:
-------------------------------------
map word_couunt;
int count = 0;
//1. Count(keyValue)
if(word_count.count("good")) count = word_count["good"];

//2. Find(keyValue)
if(word_count.find("good")!=word_count.end()) count = word_count["good"];
-------------------------------------

There was a introduction about the operation of map search in C++ Primer, Page 251. If you'd like to know more, please look it up.



Three conclusions:
1. Doing is more important than thinking.
2. C++ primer is very good. It should be read once more.
3. No hypothesis is better than any wrong ones.

没有评论:

发表评论