简体   繁体   中英

Question about accessing object method with vector iterator

I am new to c++ and I have an assignement on vector/iterators. I ran into a problem that I was able to solve by searching on the internet but unfortunately the forums I visited only provided with the solution and did not explain why it works. Here's the problem I had:

std::vector::<Student*>::iterator iter;
for (iter = v_students.begin(); iter != v_students.end(); iter++)
{
     iter*->doStuff(); // Gave me a compile error
}

I tried a long time to solve that error without success until I found on a forum someone suggesting this instead:

(*iter)->doStuff;

Placing the * in front of the iterator and putting () around it seems to do the trick but I'd like to understand why. Thanks !

You have a vector of pointers to objects.

When you iterate the vector, the object you have "in hand" is an iterator. To go from that iterator to the object in the vector you have to dereference it (the (*iter) bit). Now you have a pointer. To go from that to the actual object, you need to also dereference the pointer. That's the last (*iter)-> bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM