开发者

How do you use a C++ iterator?

I have a vector like so:

vector<MyType*> _types;

And I want to iterate over the vector and call a function on each of MyTypes in the vector, but I'm getting invalid return errors from the compiler. It appears the pos iterator isn't a pointer to MyType, it's something else. What am I not understanding?

Edit: Some code..

    for (pos = _types.begin(); pos < _types.end(); pos++)
{
    InternalType* inst = *pos->GetInternalType();
}

The compiler errors are:

  • invalid return type 'InternalType**' for overloaded 'operator ->'
  • 'GetInternalType' : is not a member of 'std::_Vector_iterator<_Ty,_Alloc>'

Edit pt2

Should my vector contain pointers or objects? What are the pros and cons? If I am using new to create an instance, I am guessing I can only use a vector开发者_JS百科 of pointers to MyType is that correct?


If the vector contained objects, not pointers, you could do pos->foo(). The iterator "acts like" a pointer. But your vector contains pointers, so an iterator will act like a pointer to a pointer, so needs to be dereferenced twice.

MyType *pMyType = *pos; // first dereference
if (pMyType) {          // make sure the pointer is not null
  pMyType->foo();       // second dereference
}

If you are sure the pointer is not null, you could do this:

(*pos)->foo();

The parenthesis around *pos are needed so the dereference applies to pos, not to pos->foo(). Order of operations.

If your vector needs to contain items from a class hierarchy (e.g., subclasses of MyType), then you have to make it a vector of pointers. Otherwise a vector of objects is probably simpler.


You've defined _types as a vector of pointers. Assuming your pos is an iterator into that vector, it's going to be an iterator to a pointer, so you'll need to dereference it twice to get to an instance of MyType.

Edit: based on what you've added to the question: You have something like *pos->whatever. Try (*pos)->whatever instead. As it stands, you're trying to use whatever as a member of the iterator, then dereference the result...


Iterators are not pointers. Iterators are types that behave like pointers. In some implementations of some containers, the iterator type may in fact be a pointer (all pointers are iterators), but this cannot be used as a general rule.

If you need to generate a pointer from an iterator, you can use &*pos, which will dereference the iterator and then get the address of the result (of course, this doesn't work if unary operator & is overloaded, but that's a whole other can of worms).


for (vector<MyType*>::iterator i = _tpes.begin(); i != _types.end(); ++i) {
  // do something with i
}


for (vector<MyType*>::iterator it = _types.begin();
     it != _types.end();
     ++it)
{
    // `*it` is this iteration's `MyType*` from your vector
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜