When I insert() an object into container such std::unordered_map, how can I get reference/iterator/pointer to its location without searching for it ( e.g. find(); that would mean unnecessary overhead ).
I mean, the container datastructure should know where it just stored my object, without searching.
consider this code:
class Node{
public:
int id;
double mass;
};
std::unordered_map<uint32_t,Node> nodes;
Node& tryInsertNode( uint32_t key, const Node& node ){
auto nod_it = nodes.find( key );
if ( nod_it == nodes.end() ){
nodes.insert( {key, node} );
nod_it = nodes.find( key ); // this is silly, I don't want to do this !!!
// nod_it = ??? // JUST GIVE ME MY POINTER !!!
}else{
nod_it->second = node;
};
return nod_it->second;
}
I need to return reference / pointer / iterator to the instance of class Node which is allocated inside std::unordered_map<uint32_t,Node> nodes; so that I can modify the contend of this node later, without paying cost of find()
Sure, I would not have this problem when I use pointers i.e. : std::unordered_map<uint32_t,Node*> nodes;
But I think that in my particular case would be std::unordered_map<uint32_t,Node> preferable for performance reasons (i.e. less jumping in memory).
Aucun commentaire:
Enregistrer un commentaire