您真的不应该尝试将习语直接从一种语言翻译成另一种语言。
在 C++ 中,您通常不会编写带有迭代器并生成新迭代器的函数;相反,您编写的函数接受输入和输出迭代器并从一个迭代器复制到另一个。因此,您可以编写一个zip
函数,它接受一个输入迭代器 over T
、一个输入迭代器 overU
和一个输出迭代器 over pair<T, U>
。
但是你不会以这种方式将两个调用链接在一起,因为你的zip
函数不会返回任何可以有效传递给任何类型dict
函数的东西(比如迭代器范围)。相反,您可以创建一个dict
模拟 (an unordered_map
),在其中创建一个输出迭代器,然后使用zip
函数将对复制到其中。
像这样的东西:
template <I1, I2, O>
void zip(I1 it1, I1 it1end, I2 it2, I2 it2end, O o) {
while ((it1 != it1end) && (it2 != it2end)) {
*o++ = std::make_pair(*it1++, *it2++);
}
}
std::unordered_map<T, U> mapping;
zip(c1.begin(), c1.end(), c2.begin(), c2.end(), std::inserter(mapping, mapping.end()));
除非我认为您实际上不能inserter
以unordered_map
这种方式使用,因此您必须改为编写一个map_inserter
函数。
如果您不知道类型T
和U
本地,您可能希望将所有这些都包装在一个函数模板中,该模板从迭代器的元素类型中提取类型,以便您可以auto
做到。(在 C++11 中,decltype
不需要函数也可以,但表达式会很乱。)
zip
如果您对and有多种用途map_inserter
,则可能值得编写它们。但除此之外,更好的解决方案是将其扩展为显式循环:
auto it1 = c1.begin(), it1end = c1.end(), it2 = c2.begin(), it2end = c2.end();
std::unordered_map<T, U> mapping;
while ((it1 != it1end) && (it2 != it2end)) {
mapping[*it1++] = *it2++;
}