遍历以向量和映射作为其第二个节点的映射,并在第二个节点的第二个元素中找到匹配项。C++

Traverse a Map that has a vector and a Map as its second Node and find a match in the second Node's second element. C++

本文关键字:第二个 节点 映射 C++ 元素 向量 遍历      更新时间:2023-10-16

如何遍历第二个映射的第二个节点并找到重复项?使用下面的代码,我期望第二个for循环迭代4次,因为在外部映射中有4个节点。然而,在第二个for循环的第一次迭代之后,我得到了一个段错误。和想法吗?

void xmlParser::SortAndGroupByKey()
{
    bool match = true;
    std::map<std::vector<unsigned char>, std::vector<unsigned char>> tempMidNonceMap;
    std::map<std::vector<unsigned char>, std::vector<unsigned char>>::iterator keyIt= m_mapMidNonceKey.begin()->second.begin();
    //Iterate thru the second maps second element
    for(std::map<std::vector<unsigned char>, std::map<std::vector<unsigned char>, std::vector<unsigned char>>>::iterator mapIt=m_mapMidNonceKey.begin(); mapIt != m_mapMidNonceKey.end(); ++mapIt)
    {
        //innerMapit points to the inner(2nd Map) map iterator
        for(std::map<std::vector<unsigned char>, std::vector<unsigned char>>::iterator innerMapit= mapIt->second.begin(); innerMapit != mapIt->second.end(); ++innerMapit)
        {
            for(size_t i = 0; i < innerMapit->second.size(); ++i)
            {
                if(innerMapit->second[i] != keyIt->second[i]) //Do they match?
                {
                    match = false;
                    break;
                }
            }
            if(match)
            {
                //Make a pair of the values
                tempMidNonceMap.insert(std::make_pair(mapIt->first,innerMapit->first)); 
            }
        }
        //Check to see if the key already exists in the map if it does then only insert 
        if(!DuplicateKeyExists(keyIt->second))
        {
            this->m_mapKey.insert(std::make_pair(keyIt->second, tempMidNonceMap));
        }
        tempMidNonceMap.clear();
        keyIt++;
        match = true;
    }
}

已解决:Map的Map不是我"认为"要填充的格式。

可能存在越界访问
innerMapit->second[i] != keyIt->second[i]

对于keyIt->second[i]

最简单的修复应该是使用
const bool match = (innerMapit->second != keyIt->second);
不是

for(size_t i = 0; i < innerMapit->second.size(); ++i)
{
    if(innerMapit->second[i] != keyIt->second[i]) //Do they match?
    {
        match = false;
        break;
    }
}
相关文章: