using iterators

Hi,

I'm trying to use an iterator to loop through a vector of pointers to my class CEntity and call their Update() method. This is my first time using an iterator and I hit a problem.

1
2
3
4
5
for (std::vector<CEntity*>::iterator iter = m_entityVector.begin(); iter!=m_entityVector.end(); iter++)
		{
			iter->Update(); // invalid return type 'CEntity **' for overloaded 'operator ->' 
                                        //'Update' : is not a member of 'std::_Vector_iterator<_Ty,_Alloc>'
		}


my m_entityVector is a vector of entities, CEntity contains a virtual update method which will be overloaded by children

 
std::vector<CEntity*>m_entityVector;
An iterator basically is a pointer to the element. Thus, if you have iter, you basically have a CEntity**, which means you have to do this:

(*iter)->Update();
You have put pointers in your vector, but your code assumes that you put the objects themselves in rather than their pointers.

So instead of iter->Update(); you need (*iter)->Update();

If you think about it *iter gives you the value which is a pointer.

So after you do *iter you then dereference the resulting pointer.

Hence:

 
(*iter)->Update();
Snap!
Post hax! I guess I win.
 
std::for_each(m_entityVector.begin(), m_entityVector.end(), std::mem_fun(&CEntity::Update));
Topic archived. No new replies allowed.