【问题标题】:Check if map contains all the keys from another map检查地图是否包含来自另一个地图的所有键
【发布时间】:2013-06-22 20:31:07
【问题描述】:

Check if map in C++ contains all the keys from another map 回答了我的问题,但我不确定我们如何同时遍历两个地图。

我知道如何遍历一个,如图所示:

typedef std::map<QString, PropertyData> TagData;
TagData original = readFileToMap("FoxHud.bak");

for (TagData::const_iterator tagIterator = original.begin(); tagIterator != original.end(); tagIterator++) {
}

【问题讨论】:

  • 使用一个while循环和两个迭代器变量。
  • 我会说 12775028 是 16045108 的副本。但是这个问题更多的是关于如何在一般意义上遍历 2 个地图(我们需要理解这个问题,与已被正确回答)。

标签: c++ map stl iterator


【解决方案1】:

试试这个方法:

// As std::map keys are sorted, we can do:

typedef std::map<string, int> TagData;
TagData map1;
TagData map2;
...
TagData::const_iterator map1It = map1.begin();
TagData::const_iterator map2It = map2.begin();

bool ok = true;
std::size_t cnt = 0;

while (map2It != map2.end() && map1It != map1.end()) {
    if (map1It->first != map2It->first) {
        map1It++;
    } else {
        map2It++;
        cnt++;
    }
}

if (cnt != map2.size()) ok = false;

cout << "OK = " << ok << endl;

这也适用于大小不同的地图。

【讨论】:

    【解决方案2】:

    如果你想同时迭代 2 个地图,你可以这样做:

    if (map1.size() != map2.size())
      ; // problem
    else
    {
      for (map<X,Y>::const_iterator it1 = map1.begin(),
                                    it2 = map2.begin();
           it1 != map1.end() && it2 != map2.end();
           ++it1 , ++it2)
      {
        // ...
      }
    }
    

    现在,如果您想以不同的“速度”遍历 2 个映射,那么使用 while 循环来分别调节 it1 和 it2 的增量会更合适。示例见Golgauth's answer

    【讨论】:

    • 但是该算法应该适用于彼此大小不同的地图!
    • 这种方式不起作用,请再次阅读先决条件:stackoverflow.com/q/12775028/1715716 = I want to verify that the intersection of the set of keys of m1 and m2 is the same as the set of keys of m2。 OP 没有要求检查两张地图是否相同......此外,此代码无法编译:tagIterator.first 应该是tagIterator-&gt;first
    • “我不确定我们如何同时遍历两个地图。”是问题。这是要求澄清原件的要求。显示如何“遍历两个地图”的解决方案不必解决 stackoverflow.com/q/12775028/1715716 中提出的问题
    • 确实,让我们专注于回答当前的问题,另一个已经回答了。然而,确实能够以不同的速度遍历 2 张地图应该是这里答案的一部分。我编辑了我的答案,现在指向 Golgauth 的答案。
    • @JonL 当然,但我们还必须关注由问题标题引发的补充问题:“检查地图是否包含来自另一个地图的所有键”。所以在我看来,这完全是问题的一部分……不是吗?好吧,没有必要为此争吵:两个答案都是互补的。
    猜你喜欢
    • 2012-09-28
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    相关资源
    最近更新 更多