矢量迭代器 [英] Vector iterators
本文介绍了矢量迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码。
vector<IRD>* irds = myotherobj->getIRDs();//gets a pointer to the vector<IRD>
for(vector<IRD>::iterator it = irds->begin(); it < irds->end(); it++)
{
IRD* ird = dynamic_cast<IRD*>(it);
ird->doSomething();
//this works (*it).doSomething();
}
这似乎失败了...我只想得到指向向量中每个元素的指针,而不使用(* it)。
This seems to fail...I just want to get the pointer to each element in the vector without using (*it). all over.
- 如何获取指向该对象的指针?
- 向量指针irds,我究竟是什么迭代?它是每个元素的副本,或者当我说(* it).doSomething(),
推荐答案
为什么要获取指针?
使用引用:
for(vector<IRD>::iterator it = irds->begin(); it != irds->end(); ++it)
{
IRD & ird = *it;
ird.doSomething();
}
或者:
for(vector<IRD>::iterator it = irds->begin(); it != irds->end(); ++it)
{
it->doSomething();
}
/ code>当比较迭代器,而不是<
。虽然在这种情况下它会工作,如果你使用不同的容器(这是迭代器的用途:抽象底层容器)它会停止工作。
Also, as everyone said, use !=
when comparing iterators, not <
. While it'll work in this case, it'll stop working if you use a different container (and that's what iterators are for: abstracting the underlying container).
这篇关于矢量迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文