简体   繁体   中英

How to use struct as key in std::map

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?

You can define the comparison operator as a freestanding function:

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

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;

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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