views:

462

answers:

2

I was using std::hash_map<char*,T> and somehow managed to make it work but have now discovered that the default compare function, euqal_to<char*> does a pointer compare rather than a string compare. I've fixed this by making my own compare type (using C's strcmp and it's about 5 LOC) but I'd be slightly shocked if there wasn't one already as part of the STL.

So, is there a comparator for doing string comparison?


Related link

A: 

The STL has a find method for the string type. This allow you to find a string in the string but you can use it for comparing 2 strings.

Otherwise you have a comparison function for std::string vars.

Any of this vars can be constructed with a char*.

Patrice Bernassola
+3  A: 

Well, std::strcmp is defined by C++ when you do #include <cstring>. The example in SGI's hash_map doc provides a strcmp-based example of making your own equality-testing function for char*'s (quoting from beginning of the SGI doc):

struct eqstr
{
  bool operator()(const char* s1, const char* s2) const
  {
    return strcmp(s1, s2) == 0;
  }
};

I have to say I agree with the author of the link in your post, where he says that it is already a mistake for hash_map<char*> to use by default a string-based hash<char*>. But I usually use hash_maps (or, lately, boost::unordered_maps) on C++ std::strings for this kind of thing anyway.

cce
I'll accept the point on the default, however I'd think providing a pre-built option would be good idea.
BCS
this is effectively what I did and I'd be surprised if the docs would use it as an example of there was a better way.
BCS
I agree, it would make sense if `namespace std` provided string-oriented alternatives for `std::less<char*>` and `std::equal<char*>`. But those should be alternative names, not specializations.
MSalters