除了 pmr 的回答和您对寻求实现指针的评论之外,“压缩”迭代器的基本思想很容易实现:
#include <iostream>
#include <vector>
template <typename T, typename U>
struct Zip
{
Zip(const T& t, const U& u, char sep = '|')
: it_(t.begin()), iu_(u.begin()), te_(t.end()), ue_(u.end()), sep_(sep)
{ }
Zip& operator*() const { return *this; }
Zip& operator++() { ++it_; ++iu_; return *this; }
operator bool() const { return it_ != te_ && iu_ != ue_; }
friend std::ostream& operator<<(std::ostream& os, const Zip& z)
{
return os << *z.it_ << z.sep_ << *z.iu_;
}
private:
typename T::const_iterator it_, te_;
typename U::const_iterator iu_, ue_;
char sep_;
};
int main()
{
std::vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
std::vector<std::string> v2;
v2.push_back("one");
v2.push_back("two");
v2.push_back("three");
v2.push_back("four");
for (Zip<std::vector<int>, std::vector<std::string> > zip(v1, v2); zip; ++zip)
std::cout << zip << '\n';
}
您可以创建一个 Zip 迭代器,其中一侧/两侧是 Zip 迭代器以处理多个(超过 2 个)迭代器,或者使用可变参数模板概括上述内容。