Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 315
dragan.stepanovic Avatar asked Mar 18 '11 14:03

dragan.stepanovic


People also ask

Can I use struct for key of map C++?

C++ You can use struct or class defined by yourself as key of std::map of C++.

Can C++ map have pair as key?

A C++ map is a way to store a key-value pair. A map can be declared as follows: #include <iostream> #include <map> map<int, int> sample_map; Each map entry consists of a pair: a key and a value.

Which tree data structure is used by map in C++?

Binary Search Tree: A binary search can also be implemented using a map, where all the key-value combinations will be in an ordered manner.

How does map store values in C++?

Maps are associative containers that store elements in a combination of key values and mapped values that follow a specific order. No two mapped values can have the same key values. In C++, maps store the key values in ascending order by default. A visual representation of a C++ map.


2 Answers

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;
like image 154
Matteo Italia Avatar answered Oct 20 '22 13:10

Matteo Italia


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.

like image 21
Jerry Coffin Avatar answered Oct 20 '22 12:10

Jerry Coffin