【发布时间】:2014-06-18 02:10:43
【问题描述】:
我正在尝试实现与 set_intersection 和 set_difference 类似的功能,但使用地图作为我的日期类型进行分配。我能够找到交集,但差异函数的输出不是我应该期待的,我不知道为什么。我正在使用的两个功能如下。
map<string, int> Group::Intersection(map<string, int> &tempSet, map<string, int> ¤tSet){
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> ¤tSet){
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。据我所知,这是从第一个地图中获取两个键并将它们与第二张地图,但我无法确定这是我的迭代还是我将键/值放入新地图时。任何建议都将不胜感激,因为我觉得这应该是一个我无法弄清楚的简单解决方案。
【问题讨论】:
-
这项作业明天必须到期。你和John Smith谈过吗?他的名字真的是约翰史密斯吗?
-
When will it be my turn? 现在!!!首先使用调试器来缩小您的问题并指定您不理解的行为!