tags:

views:

600

answers:

4

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 *"?

+2  A: 

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;  
    }
};
Kornel Kisielewicz
A: 

As far as I understand C++, it is a reference to an unsigned character pointer constant. Such a variable can be assigned only once(because it is a reference) nad it holds a pointer, which cannot change its address(because it is constant pointer) to an unsigned character which is primitive type in C++.

Gabriel Ščerbák
+1  A: 

It works for me with just unsigned char *.

Alexey Malistov
A: 

the template for the std::map expects the compare functor to accept arguments of "keytype const&" the type of your key is "unsigned char*".replacing keytype you get usigned char* const&.
The const& is first guarantees that your compare funktor does not modify the keys (const) and that only references are passed (&). In your passing a copy wouldn't cause a problem as your key is a pointer.

josefx