如何通过stl :: List循环并存储其中一个对象的值,以便稍后在函数中使用?
Particle *closestParticle;
for(list<Particle>::iterator p1 = mParticles.begin(); p1 != mParticles.end(); ++p1 )
{
// Extra stuff removed
closestParticle = p1; // fails to compile (edit from comments)
}
答案 0 :(得分:53)
要么
Particle *closestParticle;
for(list<Particle>::iterator it=mParticles.begin(); it!=mParticles.end(); ++it)
{
// Extra stuff removed
closestParticle = &*it;
}
或
list<Particle>::iterator closestParticle;
for(list<Particle>::iterator it=mParticles.begin(); it!=mParticles.end(); ++it )
{
// Extra stuff removed
closestParticle = it;
}
或
inline list<Particle>::iterator findClosestParticle(list<Particle>& pl)
{
for(list<Particle>::iterator it=pl.begin(); it!=pl.end(); ++it )
{
// Extra stuff removed
return it;
}
return pl.end();
}
或
template< typename It >
inline It findClosestParticle(It begin, It end)
{
while(begin != end )
{
// Extra stuff removed
return begin;
++begin;
}
return end;
}
这些按照个人喜好不断增加。 :)
答案 1 :(得分:1)
对于list
,使迭代器无效的唯一方法是erase
。所以我怀疑你在循环中的某个时刻正在调用list.erase(p1)
。您需要复制迭代器,将p1
移回一个,然后擦除副本。
答案 2 :(得分:0)
我不是STL的专家,但我相信它无法编译的原因是因为迭代器是指向另一个对象的对象。换句话说,迭代器是指针的泛化。因此,要对代码进行最少的更改来执行您想要的操作,首先需要取消引用迭代器以获取它包含的值。然后你会使用'&amp;'获取其地址,然后将该地址分配给指针变量。这就是为什么ptr =&amp; * it;作品。