地图插入返回错误答案的地图

Map of map insert returning incorrect answer

本文关键字:地图 答案 返回 插入 错误      更新时间:2023-10-16

我正在使用地图中的地图来跟踪一些数据。

为了添加一些数据,我首先检查我是否基于字符串形式的全局键进行跟踪。

如果我的地图中有该键,那么我会检查第一个地图内的地图,看看它是否有值,其中键作为无符号的短整型。这是结构。

map<string, fileInfo> fileMap;
class fileInfo {
public:
    unsigned short int numNeighbors;
    map<unsigned short int, neighborInfo> neighbors; //key is id
//... more
}

我能够检查我的主键是否在我的整个地图中,但是当我检查该键是否在那里时,我在插入时得到一个 false,表明这个邻居已经存在,但它不存在。我已经检查了理智,并确保查看我的密钥是否匹配,但它们不匹配。

查找第一个键

it = fileMap.find(filename);
if (it == fileMap.end()) {
//add to fileMap
}else{
    fileInfo currFI = it->second;
    neighborInfo n = createNeighbor();
    pair<it_Neighbor, bool> ret;
    map<unsigned short int, neighborInfo> neighbors = currFI.neighbors;
    ret = currFI.neighbors.insert(pair<unsigned short int, neighborInfo> (id, n));
    if (ret.second == false) {
            cout<< "Neighbor already exists for this file, ignoring duplicates."<< endl;
    } else {   
            cout << "size" << currFI.neighbors.size() << endl;
}

我的大小输出始终为 2,而它应该是 4。

我是否需要在我的类中定义任何运算符或任何内容才能使其工作?

而不是

fileInfo currFI = it->second;

尝试

fileInfo &currFI = it->second;

当 else 块结束时,currFI变量将被丢弃。您应该将其设置为fileMap项的reference,以便将其保留在那里。