简体   繁体   中英

GUID as std::map key

a dictionary was defined as the following :

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

we got a compilation error:

Error 9 error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const GUID' (or there is no acceptable conversion) c:\\program files (x86)\\microsoft visual studio 11.0\\vc\\include\\xstddef

Then we solve it as:

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; 

Now, all compiled, but then we get an exception (invalid operator< )in run time.

I have no idea what is wrong, will be glad if someone could help

The shown comparison operator can return false for both a<b and b<a when a does not compare as equal to b .

Just apply memcmp to the whole thing and check the result.


Addendum (due to sehe's comments). The GUID type, which this question is tagged with, is a Windows API name for a standard 128-bit UUID, universal unique identifier . It's guaranteed POD, and moreover guaranteed contiguous, since it's guaranteed 128 bits with every one meaningful. This makes it safe to use memcmp .

Your GUIDComparer is comparing for equality. The functor you pass to a map must generate weak ordering - ie it must compare less or compare greater, not equal.

this will work:

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

You might consider using Boost.UUID instead of GUID which is provided by Windows SDK.

#include <boost/uuid/uuid.hpp>

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

boost::uuids::uuid already provides the necessary comparison operators so you don't have to write an ordering predicate as suggested in other answers.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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