插入C++ std :: map时出现奇怪的错误

Dan*_*iel 1 c++ dictionary stdmap std c++-standard-library

我正在尝试将一些值对插入到std :: map中.在第一种情况下,我收到一个指向地图的指针,取消引用它并使用下标运算符来赋值.即

(*foo)[index] = bar;
Run Code Online (Sandbox Code Playgroud)

稍后,当我尝试迭代集合时,我返回的键/值对在除了第一个(map.begin())项之外的所有情况下都包含null属性.奇怪的是,如果我通过map的insert函数进行插入,一切都很顺利,即:

foo->insert(std::pair<KeyType,ValueType>(myKey, myValue));
Run Code Online (Sandbox Code Playgroud)

为什么会这样?这两种方法在功能上是否相同?我已经在下面粘贴了一些实际代码的片段

...
typedef std::map<int, SCNode*> SCNodeMap;
...


void StemAndCycle::getCycleNodes(SCNodeMap* cycleNodes)
{
    (*cycleNodes)[root->getId()] = root;

    SCNode* tmp = root->getSucc();
    while(tmp->getId() != root->getId())
    {
        // (*cycleNodes)[tmp->getId()] == tmp; // crashes (in loop below)
        cycleNodes->insert(std::pair<int, SCNode*>(tmp->getId(), tmp));//OK
        std::pair<int, SCNode*> it = *(cycleNodes->find(tmp->getId()));
        tmp = tmp->getSucc();
    }

    // debugging; print ids of all the SCNode objects in the collection
    std::map<int, SCNode*>::iterator it = cycleNodes->begin();
    while(it != cycleNodes->end())
    {
        std::pair<int, SCNode*> p = (*it);
        SCNode* tmp = (*it).second; // null except for it = cycleNodes->begin()
        std::cout << "tmp node id: "<<tmp->getId()<<std::endl; 
        it++;
    }

}
Run Code Online (Sandbox Code Playgroud)

我完全没有想法.有人有建议吗?

Sim*_*ele 12

在您的实际代码中,您有:

(*cycleNodes)[tmp->getId()] == tmp;
Run Code Online (Sandbox Code Playgroud)

这不会将tmp分配到地图中,而是引用到地图中创建一个空值(参见@Neil Butterworth) - 你有==而不是=.你想要的是:

(*cycleNodes)[tmp->getId()] = tmp;
Run Code Online (Sandbox Code Playgroud)