我正在尝试实现一个两级迭代器,正如我现在将描述的那样。基本上我有一个“向量向量”,我想要一个迭代器,它将遍历向量向量中的所有对象。
下面的代码做到了这一点,但它有点难看,我不能在 for 循环中声明迭代器。因此,我在 for 循环之前声明了迭代器,然后迭代,然后删除迭代器,这是 klugy。我不知道 C++,所以我在这里有点不合群,所以请不要犹豫,提供 C++ 编程建议。如何修复此代码,以便可以在 for 循环中声明迭代器?
// iterator_2.cpp
//to compile: g++ iterator_2.cpp
#include <iostream>
#include <vector>
using namespace std;
typedef double Object;
typedef vector<Object> ObjectVector;
vector<ObjectVector*> types;
class ObjectIterator{
protected:
public:
Object *object;
ObjectIterator operator++()
{object++; //increment object
// when current object is at the end for type[s] increment s and set object to the first entry in the next type
if(object==&(*(types[s])->end())){
s++;
object=&((*types[s])[0]);
}
return (*this);
}
ObjectIterator():null(0){s=0;object= &((*types[0])[0]);};
int s;
ObjectIterator *null;
};
int num_types=2;
int main(){
int num_objects[num_types];
num_objects[0]=3;
num_objects[1]=5;
// initialize objects for each type
for(int s=0;s<num_types;s++){
ObjectVector *objectlist = new ObjectVector;
for(int i=0;i<num_objects[s];i++){
objectlist->push_back((double)2*i*(s+1));
}
types.push_back(objectlist);
}
// use the two-level iterator
ObjectIterator *OI;
OI = new ObjectIterator;
for(; OI->s < num_types; ++(*OI))
{
cout << *(OI->object)<<endl;
}
delete OI;
}