GUID为std::映射键
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 studio11.0\vc\include\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;
现在,所有的都已编译,但随后我们在运行时得到一个异常(无效运算符<)。
我不知道出了什么问题,如果有人能帮助,我会很高兴
您的GUIDComparer正在进行相等性比较。传递给映射的函子必须生成弱排序,即它必须比较少或比较大,而不是相等。
这将起作用:
struct GUIDComparer
{
bool operator()(const GUID & Left, const GUID & Right) const
{
// comparison logic goes here
return memcmp(&Left , &Right,sizeof(Right)) < 0;
}
};
当a
不等于b
时,显示的比较运算符可以为a<b
和b<a
返回false
。
只需将memcmp
应用于整个事件并检查结果即可。
附录(根据sehe的意见)。此问题标记的GUID
类型是标准128位UUID的Windows API名称,通用唯一标识符。它保证POD,而且保证连续,因为它保证128位,每一位都有意义。这使得使用memcmp
是安全的。
您可以考虑使用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)
相关文章:
- 使用std::函数映射对象方法
- 使用"std::unordereded_map"映射到"std::list"对象
- C++匿名结构作为std::映射值
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 当键值是 std 向量时,为什么使用 at in C++ 访问映射值如此缓慢?
- tao_idl -Gstl 不映射 std::string
- <char> 使用 Vulkan 映射内存时如何使用 std::vector 而不是 void**?
- 附加使用 Struct 作为"multikey"并将 std::vector 用作映射值的映射
- 我可以将新的 std::tuple 放入内存映射区域,并在以后读回吗?
- 如何初始化 std::向量的映射?
- 如何将不同的函数签名映射到同一个 std::map?
- 从匿名命名空间映射的辅助值抛出 std::bad_alloc
- 将唯一指针插入std::映射
- C++ODB数据库映射程序:无法在关系中使用std::weak_ptr
- 如何在C++中迭代集合映射(std::map<std::set< char>, int >)?
- std::int 和 struct 内存不足的映射 (std::Bad_alloc) c++
- 编译器不推导模板参数(映射std::vector->std::vector)