Hi,
I'm trying to use the STL map class to be able to store keys and associated values. I started out using it with keys of pre-existing data types like int, string, etc. and was working fine. I was also able to use it with values of custom classes.
I'm now trying to use it to store keys of custom classes. To do so, it appears to require the creation of the < operator (presumably so that the map can sort the keys).
My question is this - what is the proper code inside the < operator? Below is what I have, (and it compiles and seems to work), but I'm not sure it makes sense. How would it need to change if I had other data types inside my KeyObj class as well? Also, should I somehow account for the fact that if lastName is blank on one object and firstName is blank on the other object being compared, that they might be considered equal? - would I handle that by putting a separator in between when comparing?)
class KeyObj
{
public:
string lastName;
string firstName;
bool operator< (const KeyObj &compare)
{
return lastName+firstName < compare.lastName+compare.firstName;
}
};
bool operator< (const KeyObj &source, const KeyObj &compare)
{
return source.lastName+source.firstName < compare.lastName+compare.firstName;
}
int main( int argc, char * argv[] )
{
map<KeyObj,string> myMap;
KeyObj k;
k.lastName="JONES";
k.firstName="BOB";
myMap[k] = "MR. BOB JONES";
KeyObj k2;
k2.lastName="JONES";
k2.firstName="FRED";
myMap[k2] = "MR. FRED JONES";
cout<<"Searching for FRED JONES:"<<endl;
KeyObj test;
test.lastName="JONES";
test.firstName="FRED";
if ( myMap.find(test) != myMap.end() )
{
cout<<myMap[test]<<endl;
}
else
cout<<"COULDN't FIND IT"<<endl;
------------------------
Searching for FRED JONES:
MR. FRED JONES