获取刚插入容器的对象的迭代器或引用

Get iterator or reference of object just inserted to container

当我 insert() 将一个对象放入 std::unordered_map 容器中时,我怎样才能 reference/iterator/pointer 到达它的位置而不搜索它(例如 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;
}

我需要return引用/指针/迭代器到分配在std::unordered_map<uint32_t,Node> nodes;内的class Node的实例,这样我以后就可以修改这个节点的竞争,而无需支付find()

的费用

当然,当我使用指针时我不会有这个问题,即: std::unordered_map<uint32_t,Node*> nodes;

但我认为在我的特定情况下 std::unordered_map<uint32_t,Node> 出于性能原因(即减少内存跳跃)更可取。

std::unordered_map::insert returns 新插入元素的迭代器*。

所以你已经有了。只是,目前在您的代码中,您将其丢弃。


* 好吧,还是一对包裹它。这取决于您调用的 insert。在你的情况下:

nod_it = nodes.insert( {key, node} ).first;