all groups > visual c libraries > december 2004 >
You're in the

visual c libraries

group:

C++ STL map Container


C++ STL map Container Jazzkt
12/13/2004 6:18:47 PM
visual c libraries:
I wrote a little code using the map container available in the STL of C++.
The trouble I am having is that the find() member function is working
properly. When I try to find a key, if that key is not in the map, it
should return the iterator set to the address of the end of the map.

However, when I try to find a key in the map, it returns a value that is not
equal to the end of the map. I know beforehand that it will not find the
key and I expect the find() member function to return a pointer to the end
of the map.

The data is listed after the code sample below.

The code counts the occurrences of a string in a file. It stores the string
as the key in the map and the number of occurrences as the associated value.

Please help me find the error; I have included the code below:

map<char*, int> mp;

typedef pair<char*, int> pr;

map<char*, int>::iterator it;

...

/* put the string in the map */

if (mp.empty()) {

cnt = 1;

mp.insert(pr(ipStr,cnt));

}

else {

it = mp.find(ipStr);

if (it == mp.end()) { *** This is where it jumps to the 'else' ***

// add the new ip string

cnt = 1;

mp.insert(pr(ipStr,cnt));

}

else {

// increment the count

cnt = it->second;

cnt += 1;

it->second = cnt;

}

}

<><><>

Data:

218.190.48.173:4907

65.93.204.93:4989


Re: C++ STL map Container Bo Persson
12/13/2004 8:17:21 PM

"Jazzkt" <jazz@msn.com> skrev i meddelandet
news:b2lvd.652005$mD.181208@attbi_s02...
[quoted text, click to view]

This doesn't actually store the string as the key, but the address of
the string.

If you store the next key at the same location, they (the pointers) will
always compare equal!


Try using map<std::string, int> instead!


Bo Persson

AddThis Social Bookmark Button