简体   繁体   English

映射:即使找到了密钥,Ptr Ptr也很差

[英]map: Bad Ptr even if the key was found

I have a map inside struct: 我在struct中有一个映射:

struct amountOfDist
{
        int time;
        vector<int> distVector;
        map<string,int> pairsMap;
};
amountOfDist m_tempDistStruct;

when the code runs, it crushes when I try to find a value: 当代码运行时,当我尝试查找值时会崩溃:

if(m_tempDistStruct.pairsMap.find("(1,2)")->second != 1)
{
       ...
}

I tried to isolate the command by: 我试图通过以下方式隔离命令:

map<string,int>::iterator it;
it = m_tempDistStruct.pairsMap.find("(1,2)");

and I get padptr . 而我得到padptr But when I put break point on the line: 但是当我把断点放在行上时:

it = m_tempDistStruct.pairsMap.find("(1,2)");

I can see that the map hols all the keys and values (the correct ones) and the key (1,2) exists. 我可以看到该地图包含了所有键和值(正确的键)和键(1,2)存在。

Why does the find command returns badptr ? 为什么find命令返回badptr

I will be happy for guidance. 我很乐意提供指导。

Thanks. 谢谢。

If the map really does contain the key you're looking for, then your code should work; 如果地图确实包含您要查找的密钥,那么您的代码应该可以工作; something else has gone horribly wrong if it doesn't. 如果没有的话,其他的事情就大错特错了。 However, the code is rather fragile, since it will give undefined behaviour if the key is missing. 但是,代码相当脆弱,因为如果缺少密钥,它将给出未定义的行为。

You have to check whether find succeeded before dereferencing it; 在取消引用之前,您必须检查find是否成功; if it fails, then it returns a past-the-end iterator which isn't dereferencable. 如果失败,则返回不可取消的过去的迭代器。 Alternatively, use [] which will insert a new element if it was missing. 或者,使用[]将在缺少新元素时插入新元素。

So safer versions are: 因此,更安全的版本是:

// use find and check it exists
auto found = map.find(key);
if (found != map.end() && found->second != 1)

// use [] to insert if it doesn't exist
if (map[key] != 1)

If neither of these work, or you're absolutely sure that the key must exist, then we'll need to see a complete test case to figure out what's going wrong with the code you haven't shown us. 如果以上两种方法都不起作用,或者您绝对确定密钥必须存在,那么我们将需要查看完整的测试用例,以找出未显示给我们的代码出了什么问题。

Using your code, I get totally correct behavior. 使用您的代码,我得到了完全正确的行为。 So I am pretty sure that the value you're looking for is not in the map . 因此,我很确定您要查找的值不在map

amountOfDist m_tempDistStruct;

m_tempDistStruct.pairsMap["(1,2)"] = 10;

if  (m_tempDistStruct.pairsMap.find("(1,2)")->second == 10)
{
    cout << "GOT HERE!" << endl;
}

The above code snippet adds "(1,2)" => 10 to the map, then finds it just fine. 上面的代码段将"(1,2)" => 10到地图,然后发现它很好。 I suspect the key in your map is subtly different to what you think it is. 我怀疑您地图中的键与您认为的键有细微差别。

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

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