我想要一个 C++ 中的迭代器,它只能迭代特定类型的元素。在以下示例中,我只想迭代属于 SubType 实例的元素。

vector<Type*> the_vector;
the_vector.push_back(new Type(1));
the_vector.push_back(new SubType(2)); //SubType derives from Type
the_vector.push_back(new Type(3));
the_vector.push_back(new SubType(4));

vector<Type*>::iterator the_iterator; //***This line needs to change***

the_iterator = the_vector.begin();
while( the_iterator != the_vector.end() ) {
    SubType* item = (SubType*)*the_iterator;
    //only SubType(2) and SubType(4) should be in this loop.
    ++the_iterator;
}

我将如何在 C++ 中创建这个迭代器?

最佳答案

您必须使用动态类型转换。

the_iterator = the_vector.begin();
while( the_iterator != the_vector.end() ) {
    SubType* item = dynamic_cast<SubType*>(*the_iterator);
    if( item != 0 )
       ...

    //only SubType(2) and SubType(4) should be in this loop.
    ++the_iterator;
}

关于c++ - 如何在与 C++ 中的派生类型匹配的元素上创建迭代器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/774293/

10-10 21:38