我有一些看起来像这样的代码;给定两个映射,如果两个映射中都存在first
密钥,则将两个second
值相乘,然后对所有产品求和。例如:
s1 = {{1, 2.5}, {2, 10.0}, {3, 0.5}};
s2 = {{1, 10.0}, {3, 20.0}, {4, 3.33}};
答案应该是2.5*10.0 + 0.5*20.0
,匹配键的乘积之和。
double calcProduct(std::map<int, double> const &s1, std::map<int, double> const &s2)
{
auto s1_it = s1.begin();
auto s2_it = s2.begin();
double result = 0;
while (s1_it != s1.end() && s2_it != s2.end())
{
if (s1_it->first == s2_it->first)
{
result += s1_it->second * s2_it->second;
s1_it++:
s2_it++;
}
else if (s1_it->first < s2_it->first)
{
s1_it = s1.lower_bound(s2_it->first);
}
else
{
s2_it = s2.lower_bound(s1_it->first);
}
}
return result;
}
我想重构一下,std::set_intersection
似乎接近我想要的文档an example using std::back_inserter
,但有没有办法让它在地图上工作并避免中间数组?
答案 0 :(得分:2)
您使用的代码已经非常接近set_intersect
的实施方式。我无法看到创建新地图并迭代它的任何优势。
但是我想提及你的代码有几件事。
如果你要增加你的迭代器,你就不应该让它们保持不变。
我希望在寻找等效元素时会有比命中更多的失误。我建议先进行比较:
double calcProduct( std::map<int , double> const &s1 , std::map<int , double> const &s2 )
{
auto s1_it = s1.begin();
auto s2_it = s2.begin();
double result = 0;
while ( s1_it != s1.end() && s2_it != s2.end() )
{
if ( s1_it->first < s2_it->first )
{
s1_it = s1.lower_bound( s2_it->first );
}
else if(s2_it->first < s1_it->first )
{
s2_it = s2.lower_bound( s1_it->first );
}
else
{
result += s1_it->second * s2_it->second;
s1_it++;
s2_it++;
}
}
return result;
}