In article <blsbnh$e69$2@netlx020.civ.utwente.nl>,
b.kevelham@student.utwente.nl says...
[ ... ]
[color=blue]
> due to some compatibility issues I use char* for strings. I want to use an
> STL map where I use these char* as key. But somehow this doesn't seem to
> work. The first time I add something to the map, everything works fine. But
> the second time, I check if something is already in the map using:
>
> if(mapname.find(aString) != mapname.end()){
> //routine for handeling the situation where there already is an object
> with the key aString
> }
>
> but everytime I want to add a second element to the map with a string I
> haven't used, find() still says that there already is an object with the
> given key. And if I use a mapname.count(aString) it indeed gives a number
> unequal to zero.[/color]
By default, std::map will use operator< to compare keys. When you're
using raw pointers, that won't (normally) produce useful results.
Your options are to switch to some class (such as std::string) that
overloads operator< to do something useful, or else to supply the third
parameter when you instantiate std::map:
struct cmp_str {
bool operator()(char const *a, char const *b) {
return std::strcmp(a, b) < 0;
}
};
std::map<char *, int, cmp_str> mapname;
I'd give serious thought to switching to std::string though -- you
haven't said much specific about what compatibility issues you've faced,
but unless they're _really_ major, switching to std::string will
probably be a worthwhile investment.
On another note, I generally recommend NOT checking whether the key
exists before inserting it -- I'd normally just attempt to insert the
new item, and check the return value from the insertion to see if the
key already existed. This style of coding generally simplifies the code
and (for one example) helps avoid race conditions when/if that's an
issue.
--
Later,
Jerry.
The universe is a figment of its own imagination.