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

dra*_*vic 6 c++ stl visual-studio-2005 stdmap

我想使用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 <为这种情况重载,但问题是我无法访问我想要使用的结构的代码(GUIDVC++中的结构).

这是代码片段:

//.h

#include <map>
using namespace std;

map<GUID,GUID> mapGUID;


//.cpp

GUID tempObj1, tempObj2;              
mapGUID.insert( pair<GUID,GUID>(tempObj1, tempObj2) );   
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题呢?

Mat*_*lia 10

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

bool operator<(const GUID & Left, const GUID & Right)
{
    // comparison logic goes here
}
Run Code Online (Sandbox Code Playgroud)

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

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

// ...

std::map<GUID, GUID, GUIDComparer> mapGUID;
Run Code Online (Sandbox Code Playgroud)

  • 正确的答案是`bool operator()(const GUID&left,const GUID&right)const` (2认同)