I want to add unordered_map
to my app to store values as <string,object>
pairs. I wanted to add element to map in function, return pointer to this object, do some logic and later retrieve this value.
Unfortunately I cannot do as planned, because it looks like my reference is loosing somehow connection. This is how insertion is currently done:
std::unordered_map<std::string, EdgeS> edges;
// Some extra stuff
EdgeS* Node::insertEdge(Node* to)
{
EdgeS edge = edges[to->name];
if(!edge.to)
edge.to = to;
edge.frequency++;
edge.packets_number++;
return &edge;
}
As you can see I am using operator[] , but when later I am trying to use this map's object it looks like it is recreated and everything I've done on it has no effect.
I've been thinking also about insert , but I am not sure about difference. With operator good thing is that it doesn't matter if object exists or not I can still have reference to it. But apparently I cannot do anything with this object. So what is better in this case?
it looks like my reference is loosing somehow connection
You're not using a reference. You're making a copy:
EdgeS edge = edges[to->name];
If you want to use a reference, edge
should have type EdgeS &
.
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.