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 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.If you are sure the pointer is not null, you could do this:
The parenthesis around
*posare needed so the dereference applies topos, not topos->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.