问题描述
我想使用一个 std::map
,它的键和值元素是结构.
I want to use a std::map
whose key and value elements are structures.
我收到以下错误:error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)': 无法推导出 'const std::basic_string<_Elem 的模板参数,_Traits,_Alloc>&'来自'const GUID
我知道我应该在这种情况下重载 operator <
,但问题是我无权访问我想要使用的结构的代码 (GUID VC++ 中的结构).
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++).
这是代码片段:
//.h
#include <map>
using namespace std;
map<GUID,GUID> mapGUID;
//.cpp
GUID tempObj1, tempObj2;
mapGUID.insert( pair<GUID,GUID>(tempObj1, tempObj2) );
如何解决这个问题?
推荐答案
您可以将比较运算符定义为独立函数:
You can define the comparison operator as a freestanding function:
bool operator<(const GUID & Left, const GUID & Right)
{
// comparison logic goes here
}
或者,因为通常 a <运算符对 GUID 没有多大意义,您可以改为提供自定义比较函子作为
std::map
模板的第三个参数:
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:
struct GUIDComparer
{
bool operator()(const GUID & Left, const GUID & Right) const
{
// comparison logic goes here
}
};
// ...
std::map<GUID, GUID, GUIDComparer> mapGUID;
这篇关于如何在 std::map 中使用结构作为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!