如何在C++中匹配派生类型的元素上创建迭代器?

Ale*_*x B 3 c++ iterator stl

我想在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;
}
Run Code Online (Sandbox Code Playgroud)

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

Jem*_*Jem 9

您必须使用动态强制转换.

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;
}
Run Code Online (Sandbox Code Playgroud)