-
STL map comparing keys
An STL map I have relates char pointers to HMODULEs. Unfortunately this means that functions such as Map.count() compare the the value of the char pointer, ie the address, instead of the contents. This means that in a certain function, the char pointer passed to Map.count() always has the same value in it, but may point to a different string.
My question is, should I switch to a 'string' (which I suppose will work fine with its equality operator) or is there an easy way to make the char pointers work?
-
Code:
#include <iostream>
#include <string>
#include <map>
#include <cstdio>
using namespace std;
struct CStrCmp : public binary_function <const char*, const char*, bool>
{
bool operator()(
const char* Left,
const char* Right
) const
{
return (strcmp(Left, Right) < 0);
}
};
int main(void)
{
map<char*, string, CStrCmp> str_map;
char hello_str[] = "Hello";
char test_str[] = "Test";
char boo_str[] = "boo!!";
str_map["Hello"] = string("Goodbye");
str_map["Test"] = string("Another Test");
str_map[boo_str] = string("You have been booed!");
cout << str_map["Hello"] << endl;
cout << str_map["Test"] << endl;
cout << str_map["boo!!"] << endl;
cout << str_map[hello_str] << endl;
cout << str_map[test_str] << endl;
cout << str_map[boo_str] << endl;
cout << str_map.count(hello_str) << endl;
cout << str_map.count(test_str) << endl;
cout << str_map.count("boo!!") << endl;
cout << str_map.count("Failure Test") << endl;
cin.get();
return 0;
}
I figured this out by noting that the default compare function is documented as less<Key>, then looking up the less class and basically copying it.
-
>I figured this out by noting that the default compare function is documented as less<Key>,
>then looking up the less class and basically copying it.
You can also pass a predicate as the first constructor argument.
-
>> You can also pass a predicate as the first constructor argument. <<
Could you elaborate on that? I looked up what a "predicate" is, but I can't figure out where one would use it in this context. The first template argument to map seems to expect a type. Thanks.
-
>I looked up what a "predicate" is, but I can't figure out where one would use it in this context.
A good example would be less. It's a predicate in that it returns a truth value. It's also an object, so it would fit within the context of that parameter. However, I wasn't trying to suggest that that way is better. In fact, it has a few annoying pitfalls that make the more common solution that you posted preferable. :) I was just mentioning an alternative.