加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 06:49:02 所属栏目:百科 来源:网络整理
导读:我想在C中使用一个只能迭代特定类型元素的迭代器.在以下示例中,我想仅迭代SubType实例的元素. vectorType* the_vector;the_vector.push_back(new Type(1));the_vector.push_back(new SubType(2)); //SubType derives from Typethe_vector.push_back(new Type
我想在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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读