如何在与 C++ 中的派生类型匹配的元素上创建迭代器?
我想要一个 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++ 中创建这个迭代器?
I'd like an iterator in C++ that can only iterate over elements of a specific type. In the following example, I want to iterate only on elements that are SubType instances.
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;
}
How would I create this iterator in C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
增强过滤器迭代器?
boost filter iterator?
您必须使用动态强制转换。
You must use a dynamic cast.
没有升压的解决方案。 但是,如果您有权访问 boost 库 - 请按照建议使用 Filter Iterator。
Solution without boost. But if you have an access to the boost library - use Filter Iterator as was proposed.
正如 Paintballbob 在评论中所说,您应该创建自己的迭代器类,也许继承自
vector::iterator
。 特别是,您需要实现或覆盖operator++()
和operator++(int)
以确保跳过非 SubType 对象(您可以使用dynamic_cast
SubType*>()
来检查每个项目)。 在 O'Reilly Net 文章。As paintballbob said in a comment, you should create your own iterator class, perhaps inheriting from
vector<Type*>::iterator
. In particular, you will need to implement or overrideoperator++()
andoperator++(int)
to ensure that you skip non-SubType objects (you can usedynamic_cast<SubType*>()
to check each item). There is a nice overview of implementing your own container and iterator in this O'Reilly Net article.这是使用 boost 迭代器的另一种方法。 这次,使用 std::remove_copy_if :
它将调用一个函数(在本例中为
someFunction
)。但它可以是 boost::bind 可以构造的任何东西 - 也是一个成员 -函数)对于每个指向SubType
的指针。Just another way how to do it using boost iterators. This time, using
std::remove_copy_if
:It will call a function (In this example
someFunction
. But it can be anything boost::bind can construct - also a member-function) for each pointer that's pointing to aSubType
.