STL使用自定义比较函数对象映射 [英] STL Map with custom compare function object

查看:143
本文介绍了STL使用自定义比较函数对象映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用STL的Map容器​​通过使用二进制数据作为键来查找指针,所以我写了这个自定义函数对象:

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

并使用它:

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

这个编译似乎工作,但我不知道什么是unsigned char * const& ;类型是,为什么它不工作只是unsigned char *?

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

推荐答案

您需要提供一个比较器,不修改传递的值,因此const(注意它适用于指针而不是char)。对于引用运算符(& ),您不需要它 - 它是可选的。这也将编译:

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

这篇关于STL使用自定义比较函数对象映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆