简体   繁体   English

关于向量迭代器访问对象方法的问题

[英]Question about accessing object method with vector iterator

I am new to c++ and I have an assignement on vector/iterators.我是 C++ 的新手,我对向量/迭代器有一个分配。 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).要从该迭代器转到向量中的对象,您必须取消引用它( (*iter)位)。 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.这是最后一个(*iter)->位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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