【问题标题】:Get iterator or reference of object just inserted to container获取刚刚插入容器的对象的迭代器或引用
【发布时间】: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&lt;uint32_t,Node&gt; nodes;内部的class Node的实例,以便我以后可以修改该节点的竞争,而无需支付find()的成本

当然,当我使用指针时我不会遇到这个问题,即: std::unordered_map&lt;uint32_t,Node*&gt; nodes;

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

【问题讨论】:

    标签: c++ c++11 iterator containers


    【解决方案1】:

    std::unordered_map::insert 为新插入的元素返回一个迭代器*。

    所以你已经拥有它了。只是,此刻在你的代码中,你把它扔掉了。


    * 好吧,或者一对包裹它。这取决于你打电话给哪个insert。在你的情况下:

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

    【讨论】:

    • 是的,你是对的,我没有仔细阅读std::unordered_map::insert() 的引用,我希望插入应该返回指针/引用/迭代器到Node,而不是Pair&lt;Iterator&lt;Pair&lt;key,Node&gt;&gt;,bool&gt; ... 所以我被错误信息弄糊涂了。
    猜你喜欢
    • 1970-01-01
    • 2015-04-21
    • 2018-05-14
    • 1970-01-01
    • 2011-07-31
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多