繁体   English   中英

GUID为std :: map键

[英]GUID as std::map key

字典定义如下:

typedef boost::tuple<conn_ptr, handler_ptr, rdp_ptr> conn_tuple;
typedef std::map<GUID, conn_tuple> conn_map; 

我们遇到了编译错误:

错误9错误C2678:二进制'<':找不到运算符,它接受类型为'const GUID'的左手操作数(或者没有可接受的转换)c:\\ program files(x86)\\ microsoft visual studio 11.0 \\ vc \\包括\\ xstddef

然后我们解决它:

struct GUIDComparer
{
    bool operator()(const GUID & Left, const GUID & Right) const
    {
        // comparison logic goes here
        if( (Left.Data1 == Right.Data1) && (Left.Data2 == Right.Data2) && 
            (Left.Data3 == Right.Data3) && (memcmp(Left.Data4 , Right.Data4,sizeof(Right.Data4))==0)  )
        {   
            return true;
        }
        return false;
    }
};
typedef boost::tuple<conn_ptr, handler_ptr, rdp_ptr> conn_tuple;
typedef std::map<GUID, conn_tuple, GUIDComparer> conn_map; 

现在,所有编译,但然后我们在运行时得到一个异常(无效的运算符<)。

我不知道出了什么问题,如果有人可以提供帮助,我会很高兴

a不比较等于b时,所示的比较运算符可以为a<bb<a返回false

只需将memcmp应用于整个事物并检查结果。


附录(由于sehe的评论)。 此问题标记为的GUID类型是标准128位UUID( 通用唯一标识符 )的Windows API名称。 它保证了POD,而且保证连续,因为它保证128位,每一个都有意义。 这样可以安全地使用memcmp

您的GUIDComparer正在比较是否相等。 传递给地图的仿函数必须生成弱排序 - 即它必须比较少或比较更大,不相等。

这将工作:

struct GUIDComparer
{
    bool operator()(const GUID & Left, const GUID & Right) const
    {
        // comparison logic goes here
        return memcmp(&Left , &Right,sizeof(Right)) < 0;
    }
};

您可以考虑使用Boost.UUID而不是Windows SDK提供的GUID。

#include <boost/uuid/uuid.hpp>

typedef std::map<boost::uuids::uuid, conn_tuple> conn_map;

boost::uuids::uuid已经提供了必要的比较运算符,因此您不必像其他答案中所建议的那样编写排序谓词。

struct GUIDComparer
{
    bool operator()(const GUID & Left, const GUID & Right) const
    {enter code here
        // comparison logic goes here
        return memcmp(&Left , &Right,sizeof(Right)) < 0;
    }
};

sometimes this does not work.

it should be: return memcmp(&Left , &Right,sizeof(Right)) == -1; (not 0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM