class MyClass {
std::vector<int> vi;
std::vector<string> vs;
}
我想MyClass
用一个迭代器遍历所有集合,即遍历所有的vi,然后遍历所有的vs vs
,并且vi
没有1:1的关系(所以我不能使用元组基于迭代的方法)。这是我遇到的一个编程问题。
迭代器设计模式适用于相同类型的集合,从内部表示抽象访问。它的接口对于模拟这个问题很有用,但是集合之间的类型差异让我很难过。
我喜欢从使用的角度来解决这个问题。
MyClass mc;
... // push elements into mc
for( MyClassIterator it = mc.begin();
it != mc.end();
it++)
{
// *it can be either an int or a string
// operator * for the iterator cannot return a common type! :(
}
我什至不确定如何考虑 MyClassIterator 的设计,因为集合中的类型不同(示例中为 int、string)。
编辑:澄清一下,这是我遇到的一个编程问题。我想不出任何明智/优雅的东西,因此我在这里问它。