Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL Map with custom compare function object

Tags:

c++

stl

I want to use the STL's Map container to lookup a pointer by using binary data as a key so I wrote this custom function object:

struct my_cmp
{
    bool operator() (unsigned char * const &a, unsigned char * const &b)
    {
        return (memcmp(a,b,4)<0) ? true : false;  
    }
};

And using it like this:

map<unsigned char *, void *, my_cmp> mymap;

This compiles and seems to work, but I'm not sure what an "unsigned char * const &" type is and why it didn't work with just "unsigned char *"?

like image 896
dvl Avatar asked Jan 13 '10 15:01

dvl


1 Answers

You need to provide a comparator that guarantees non-modifying of the passed values, hence the const (note that it applies to the pointer not the char). As for the reference operator (&), you don't need it -- it's optional. This will also compile:

struct my_cmp
{
    bool operator() (unsigned char * const a, unsigned char * const b)
    {
        return memcmp(a,b,4) < 0;  
    }
};
like image 74
Kornel Kisielewicz Avatar answered Oct 28 '22 15:10

Kornel Kisielewicz