【问题标题】:Map of map insert returning incorrect answer地图插入返回错误答案的地图
【发布时间】:2014-03-31 08:32:00
【问题描述】:

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

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

如果我的地图中有那个键,我会检查第一个地图中的一个地图,看看它是否有一个值,键是一个无符号的短整数。这是结构。

map<string, fileInfo> fileMap;

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

我能够检查我的主键是否在我的整体地图中,但是当我检查该键是否在其中时,我在插入时得到一个错误,表明这个邻居已经存在,但它没有吨。我进行了健全性检查,并确保查看我的密钥是否匹配,但它们不匹配。

找到第一个键

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。

我是否需要在我的类中定义任何运算符或任何内容才能使这项工作正常进行?

【问题讨论】:

  • 如何检查密钥是否存在?
  • 你应该真的也发布访问代码。
  • 金徽章,1000+ 代表和 1+ 年会员,你应该知道的更清楚......
  • 已更新。我理解这可能是 c 大师的第二天性,但我并不熟悉它。
  • currFI 在else 块结束时被丢弃,更改永远不会影响fileMap

标签: c++ class map find


【解决方案1】:

而不是

fileInfo currFI = it->second;

试试

fileInfo &currFI = it->second;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多