简体   繁体   English

使用[]和insert()插入std :: unordered_map有什么区别?

[英]What is the difference in insertion to std::unordered_map with [] and insert()

I want to add unordered_map to my app to store values as <string,object> pairs. 我想将unordered_map添加到我的应用中以将值存储为<string,object>对。 I wanted to add element to map in function, return pointer to this object, do some logic and later retrieve this value. 我想添加元素以映射到函数中,返回指向该对象的指针,执行一些逻辑,然后再检索此值。

Unfortunately I cannot do as planned, because it looks like my reference is loosing somehow connection. 不幸的是,我无法按计划进行,因为我的参考似乎失去了某种联系。 This is how insertion is currently done: 当前是这样完成插入的:

std::unordered_map<std::string, EdgeS> edges;

// Some extra stuff

EdgeS* Node::insertEdge(Node* to)
{
    EdgeS edge = edges[to->name];
    if(!edge.to)
        edge.to = to;
    edge.frequency++;
    edge.packets_number++;
    return &edge;
}

As you can see I am using operator[] , but when later I am trying to use this map's object it looks like it is recreated and everything I've done on it has no effect. 如您所见,我正在使用operator [] ,但是稍后我尝试使用此地图的对象时,看起来好像已重新创建它,而我对此所做的一切都没有效果。

I've been thinking also about insert , but I am not sure about difference. 我也一直在考虑insert ,但是我不确定差异。 With operator good thing is that it doesn't matter if object exists or not I can still have reference to it. 使用运算符的好处是,对象是否存在无关紧要,我仍然可以引用它。 But apparently I cannot do anything with this object. 但是显然我不能用这个对象做任何事情。 So what is better in this case? 那么在这种情况下哪个更好?

it looks like my reference is loosing somehow connection 看来我的参考资料以某种方式失去了联系

You're not using a reference. 您没有使用参考。 You're making a copy: 您正在复制:

EdgeS edge = edges[to->name];

If you want to use a reference, edge should have type EdgeS & . 如果要使用参考, edge类型应为EdgeS &

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM