1
当我将insert()
对象放入容器如std::unordered_map中时,如何在不搜索它的情况下获取其位置的引用/迭代器/指针(例如find()
;这意味着不必要的开销)。获取迭代器或只是插入到容器中的对象的引用
我的意思是,容器数据结构应该知道它刚刚存储我的对象的位置,而不搜索。
考虑下面的代码:
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;
}
我需要引用/指针/迭代器返回到其内部std::unordered_map<uint32_t,Node> nodes;
这样分配的,我可以修改这个节点后的角逐,而无需支付成本的class Node
实例find()
当然,我也不会当我使用指针,即这个问题: std::unordered_map<uint32_t,Node*> nodes;
但我认为,在由于性能原因,我的特例是std::unordered_map<uint32_t,Node>
。少跳内存)。
是的,你说得对,我没看过性病的'参考:: unordered_map ::插入()'仔细了,我预计应该插入指针/引用/迭代器返回'节点',而不是'Pair>,bool>'...所以我被错误信息弄糊涂了。 –