Reputation: 4509
Lets say I have a struct as value
struct Friend { Person * a, Person* b}
Then I have another class as key
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
// After Edit from Zan
// error: no matching function for call to 'Friend::Friend()'
struct Friend {
Friend(Person* x, Person* y){
a = x;
b = y;
}
Person * a;
Person* b;
}
Upvotes: 0
Views: 1644
Reputation: 54325
No one has really addressed the error you had. I assume your commented out error here:
// my_map[r] = Friend(p1, p2); /// also does not work
// error: no matching function for call to 'A::A()'
Is from previous code and A::A()
is actually Friend::Friend()
. What that error is about is that my_map[r]
has to first create a default Friend
value before it can do anything else. The operator[]
function has to have something it can return a reference to.
If you define a default constructor that sets your Person*
values to NULL or nullptr or 0 then your code will start working, except for the other problems that have been pointed out.
Don't worry about performance here. In optimization, the compiler will see that the values are written to 0 then written to the real value without ever being read and it will remove the first writes to 0.
Upvotes: 2
Reputation: 133577
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.
Upvotes: 2
Reputation: 368
Try removing new. You are trying to store a Friend* in the map rather than a Friend. If you skipped the new, it should create one one the stack then move it into the map.
Upvotes: 0