簡體   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