繁体   English   中英

如何在std :: map中使用struct作为键

[英]How to use struct as key in std::map

我想使用std::map其键和值元素是结构。

我收到以下错误: 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

我明白我应该重载operator <为那种情况,但问题是我无法访问我想要使用的结构的代码(VC ++中的GUID结构)。

这是代码片段:

//.h

#include <map>
using namespace std;

map<GUID,GUID> mapGUID;


//.cpp

GUID tempObj1, tempObj2;              
mapGUID.insert( pair<GUID,GUID>(tempObj1, tempObj2) );   

如何解决这个问题呢?

您可以将比较运算符定义为独立函数:

bool operator<(const GUID & Left, const GUID & Right)
{
    // comparison logic goes here
}

或者,因为通常一个<运算符对GUID没有多大意义,你可以改为提供一个自定义比较函子作为std::map模板的第三个参数:

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

// ...

std::map<GUID, GUID, GUIDComparer> mapGUID;

您用作密钥的任何类型都必须提供严格的弱排序。 您可以提供比较器类型作为第三个模板参数,或者您可以为您的类型重载operator<

没有operator <for GUIDS,因此您必须提供比较运算符或使用其他键。

可能正在使用继承自GUID的类,在其中实现operator <将是一种解决方法吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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