How to use struct as a key in std :: map

I want to use std::map , whose key elements and values ​​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 in this case I have to overload operator < , but the fact is that I do not have access to the code of the structure that 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?

+6
c ++ stl visual-studio-2005 stdmap
source share
4 answers

You can define the comparison operator as a standalone function:

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

Or, since in general the a <operator does not make much sense for the GUID, you can instead provide an arbitrary comparison functor as the third argument to 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; 
+10
source share

Any type that you use as a key must provide a strict weak order. You can provide a comparator type as the third argument to the template, or you can overload operator< for your type.

+2
source share

There is no <operator for GUIDS, so you either had to provide a comparison operator, or use a different key.

0
source share

Can a class inherited from a GUID be used in which you implement the <operator will be a workaround for you?

0
source share

All Articles