【发布时间】:2016-04-23 16:59:23
【问题描述】:
当我将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> 更可取。
【问题讨论】:
标签: c++ c++11 iterator containers