c++ - 如何找到两张 map 的差异?

标签 c++ dictionary

我正在尝试实现与 set_intersection 和 set_difference 类似的函数,但使用 map 作为分配的日期类型。我能够找到交集,但差函数的输出不是我所期望的,我无法弄清楚为什么。我正在使用的两个函数如下。

map<string, int> Group::Intersection(map<string, int> &tempSet, map<string, int> &currentSet){
    map<string, int>::const_iterator input_iterator;
    map<string, int> result;
    typename map<string, int>::const_iterator it1 = tempSet.begin();
    typename map<string, int>::const_iterator it2 = currentSet.begin();

    while (it1 != tempSet.end() && it2 != currentSet.end())
    {
        if (it1->first < it2->first)
            ++it1;
        else if (it2->first < it1->first)
            ++it2;
        else{
            result.insert(make_pair(it2->first, min(it1->second, it2->second)));
            ++it1;
            ++it2;
        }
    }

    return result;
}

map<string, int> Group::Difference(map<string, int> &tempSet, map<string, int> &currentSet){
    map<string, int>::const_iterator input_iterator;
    map<string, int> result;
    typename map<string, int>::const_iterator it1 = tempSet.begin();
    typename map<string, int>::const_iterator it2 = currentSet.begin();

    while (it1 != tempSet.end() && it2 != currentSet.end())
    {
        if (it1->first < it2->first){
            result.insert(make_pair(it1->first, abs(it1->second - it2->second)));
            ++it1;
        }
        else if (it2->first < it1->first){
            result.insert(make_pair(it2->first, abs(it1->second - it2->second)));
            ++it2;
        }
        else{            
            ++it1;
            ++it2;
        }
    }
    return result;
}

使用这两个列表:

cat 5
dog 4
bear 2
dinosaur 1

cat 6
dog 4
snake 3
lion 4

我收到了猫 5 和狗 4 的交集,但差异给了我熊 4 和恐龙 3。据我所知,这是从第一个 map 中获取两个键并将它们与来自第一个 map 的值进行匹配第二张 map ,但我无法确定这是否是我的迭代,或者何时将键/值放入新 map 中。任何建议将不胜感激,因为我觉得这应该是一个我无法弄清楚的简单解决方案。

最佳答案

您的集合差异的问题是,完成迭代后,任一列表中可能都会留下元素。因此,在 wile 循环之后,您需要添加:

while (it1 != tempSet.end()) //add remaining elements from first map
{
  result.insert(*it1++);
}
while (it2 != currentSet.end()) //add remaining elements from second map
{
  result.insert(*it2++);
}

关于c++ - 如何找到两张 map 的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24276045/

相关文章:

c++ - glMultMatrix 在 glBegin() 内部不起作用

c++ - 用于获取多个容器引用的可变参数模板

python 3 保存字典

python - 在字典中使用多个键指向同一值时发生键错误

c++ - 在 Linux 平台上从 Node.js 连接到 DB2

c++ - 在一系列方程式上使用 boost::bisect

java - Jackson:将动态字段添加到 Map 序列化(比如 @JsonAppend)

javascript - 从字符串中返回一个单词

c++ - 成员函数的部分特化

python - 使用 python 2.7 中的列表推导式将对象值列表连接到字符串中