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

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

我想将 unordered_map 添加到我的应用程序以将值存储为 <string,object> 对。我想在函数中添加元素到映射,return 指向这个对象的指针,做一些逻辑然后检索这个值。

不幸的是,我无法按计划进行,因为看起来我的参考正在失去某种联系。这是当前完成插入的方式:

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;
}

如您所见,我正在使用 operator[],但稍后我尝试使用这张地图的对象时,它看起来像是重新创建的,我对它所做的一切都没有效果。

我也在考虑 insert,但不确定两者之间的区别。使用运算符的好处是对象是否存在并不重要,我仍然可以引用它。但显然我不能用这个对象做任何事情。那么在这种情况下什么更好?

it looks like my reference is loosing somehow connection

您没有使用参考。您正在复制:

EdgeS edge = edges[to->name];

如果要使用引用,edge 的类型应为 EdgeS &