用于向量遍历的C ++迭代器,可能的问题 [英] C++ iterator for vector traversal, possible issue
问题描述
大家好!
所以我还有另一个问题。
我必须遍历矢量并使用迭代器打印出这些值。
我知道你说....这有多难?
我的想法一样,所以我喜欢这个
Hi all!
So I have another problem.
I have to traverse the vector and print out the values using an iterator.
I know you say.... how hard can that be?
I thought the same so i did like this
// suppose we have a vector that takes a pointer to an object of abstract class
// like this
std::vector<foo*> myVector(5); // declared a vector
// a print method just prints data of each object in the vector
for(int a = 0; a < myVector.size()-1; a++){
myVector.at(a)->print();
}
// this works but using an iterator doesnt. Why?
// suppose we have this traversal
for(std::vector<foo*>::iterator a = myVector.begin(); i != myVector.end(); ++a){
// trying to print out each object
cout << *a << endl;
// of course it won't work why? first can't even get to print function
// second trying to access the object of an abstract class by derefencing the pointer.
// Oh and this, by dereferencing i cout the address of it but can't print out with print function
}
好的,我希望我没有犯过任何粗心的错误。
请检查我的代码并告诉我我是否正在做任何事情错误。
据我所知,我不能取消引用抽象类的指针,因为这样会留下一个对象,但是这个对象不存在。
用iterator可以做到吗?
提前致谢!
我尝试了什么:
尝试了解问题的方式。
Ok i hope i didn't make any careless mistakes.
Please check my code and tell me whether i'm doing anything wrong.
As far as i know i can't dereference a pointer to abstract class since that would leave me with an object but this object doesn't exsist.
Is it possible to do it with iterator?
Thanks in advance!
What I have tried:
Tried the way it is written in the body of the problem.
推荐答案
for(int a = 0; a < myVector.size()-1; a++){
myVector.at(a)->print();
}
你确定这个循环不会错过向量中的最后一个位置吗?
[UpDate]
Are you sure this loop don't miss the last place in the vector ?
[UpDate]
它从零到大小 - 1
It goes from zero to size - 1
你的代码停止在 size-1
之前,它停在 size-2
,再次检查。
your code stops before size-1
, so it stops at size-2
, check again.
您可能想要
cout << (*a)->print() << endl;
实际上 * a
将是指向<$ c的指针$ c> foo 。
就指针指向某个东西,你可以取消引用它。关于抽象类指针的注释没有任何意义。
In fact *a
would be a pointer to foo
.
As far a pointer point to something, you can dereference it. The comment about a pointer to abstract class does not make any sense.
这篇关于用于向量遍历的C ++迭代器,可能的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!