我想在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 ++中创建此迭代器?
答案 0 :(得分:12)
答案 1 :(得分: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;
}
答案 2 :(得分:4)
没有提升的解决方案。但是,如果您可以访问boost库 - 请按照建议使用Filter Iterator。
template <typename TCollection, typename T>
class Iterator
{
public:
typedef typename TCollection::iterator iterator;
typedef typename TCollection::value_type value_type;
Iterator(const TCollection& collection,
iterator it):
collection_(collection),
it_(it)
{
moveToNextAppropriatePosition(it_);
}
bool operator != ( const Iterator& rhs )
{
return rhs.it_ != it_;
}
Iterator& operator++()
{
++it_;
moveToNextAppropriatePosition(it_);
return *this;
}
Iterator& operator++(int);
Iterator& operator--();
Iterator& operator--(int);
value_type& operator*()
{
return *it_;
}
value_type* operator->()
{
return &it_;
}
private:
const TCollection& collection_;
iterator it_;
void moveToNextAppropriatePosition(iterator& it)
{
while ( dynamic_cast<T*>(*it) == NULL && it != collection_.end() )
++it;
}
};
class A
{
public:
A(){}
virtual ~A(){}
virtual void action()
{
std::cout << "A";
}
};
class B: public A
{
public:
virtual void action()
{
std::cout << "B";
}
};
int main()
{
typedef std::vector< A* > Collection;
Collection c;
c.push_back( new A );
c.push_back( new B );
c.push_back( new A );
typedef Iterator<Collection, B> CollectionIterator;
CollectionIterator begin(c, c.begin());
CollectionIterator end(c, c.end());
std::for_each( begin, end, std::mem_fun(&A::action) );
}
答案 3 :(得分:2)
正如paintballbob在评论中所说,你应该创建自己的迭代器类,也许继承自vector<Type*>::iterator
。特别是,您需要实现或覆盖operator++()
和operator++(int)
以确保跳过非SubType对象(您可以使用dynamic_cast<SubType*>()
检查每个项目)。在O'Reilly Net article中可以很好地概述实现自己的容器和迭代器。
答案 4 :(得分:2)
另一种方法是如何使用boost迭代器来完成它。这一次,使用std::remove_copy_if
:
std::remove_copy_if(v.begin(), v.end(),
boost::make_function_output_iterator(boost::bind(&someFunction, _1)),
!boost::lambda::ll_dynamic_cast<SubType*>(boost::lambda::_1));
它将调用一个函数(在本例中为someFunction
。但它可以是boost :: bind可以构造的任何东西 - 也是一个成员函数),用于指向SubType
的每个指针。 / p>