STL Map with custom compare function object

给你一囗甜甜゛ 提交于 2020-01-11 04:38:11

问题


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


回答1:


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;  
    }
};



回答2:


It works for me with just unsigned char *.



来源:https://stackoverflow.com/questions/2057610/stl-map-with-custom-compare-function-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!