如何在 std::map 中使用 struct 作为键
我想使用一个 std::map
,其键和值元素是结构。
我收到以下错误: 错误 C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)':无法推导出 'const std::basic_string<_Elem 的模板参数,_Traits,_Alloc> &' from 'const GUID
我知道我应该在这种情况下重载operator <
,但问题是我无权访问我想要使用的结构的代码(< VC++ 中的 code>GUID 结构)。
这是代码片段:
//.h
#include <map>
using namespace std;
map<GUID,GUID> mapGUID;
//.cpp
GUID tempObj1, tempObj2;
mapGUID.insert( pair<GUID,GUID>(tempObj1, tempObj2) );
如何解决这个问题?
I want to use a std::map
whose key and value elements are structures.
I get the following error:error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const GUID
I understand that I should overload operator <
for that case, but the thing is I don't have access to the code of the structure I want to use (GUID
structure in VC++).
Here's the code snippet:
//.h
#include <map>
using namespace std;
map<GUID,GUID> mapGUID;
//.cpp
GUID tempObj1, tempObj2;
mapGUID.insert( pair<GUID,GUID>(tempObj1, tempObj2) );
How to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将比较运算符定义为独立函数:
或者,因为一般来说 <<运算符对于 GUID 来说没有多大意义,您可以提供一个自定义比较函子作为 std::map 模板的第三个参数:
You can define the comparison operator as a freestanding function:
Or, since in general a < operator does not make much sense for GUIDs, you could instead provide a custom comparison functor as the third argument of the
std::map
template:用作键的任何类型都必须提供严格的弱排序。您可以提供比较器类型作为第三个模板参数,也可以为您的类型重载
operator<
。Any type you use as a key has to provide a strict weak ordering. You can supply a comparator type as a third template argument, or you can overload
operator<
for your type.没有运算符 <对于 GUIDS,因此您必须提供比较运算符或使用不同的密钥。
There is no operator < for GUIDS so you either have to provide the comparison operator or use a different key.
可能正在使用从 GUID 继承的类,在其中实现运算符 <;对你来说是一个解决方法吗?
May be using class inherited from GUID in which you implement operator < would be a workaround for you?