solti solti - 6 months ago 51
C++ Question

How to map pointer to object in unordered_map?

Lets say I have a struct as


struct Friend { Person * a, Person* b}

Then I have another class as

class Relation;

Now I want to create a key value relation

std::unordere_map<Relation*, Friend> my_map;

I have tried

Relation* r;
Person * p1;
Person * p2;
my_map[r] = {p1, p2}; // works

my_map[r] = new Friend(p1,p2); // does not work
// error says : error: no match for 'operator='

// my_map[r] = Friend(p1, p2); /// also does not work
// error: no matching function for call to 'A::A()'

struct Friend {
Friend(Person* x, Person* y){
a = x;
b = y;

Person * a;
Person* b;


Friend != Friend*. If you declare a std::unordered_map which has Friend as values then you can't use a Friend* and viceversa.

But I don't get what you are trying to do. It sounds like an XY problem to me. What's the purpose of Relation class? It's just to express the relationship between Person* a and b? If that's the case then the data structure is not suitable for your purpose.

By using std::unordered_map<Relation*, Friend> you are using pointers as keys but who manages the memory for Relation? Who owns it?

Maybe you just need a std::unordered_map<Person*, Person*> to store a mutual relation, or std::set<Friend> if you want to trade performance to avoid storing transitive entries.