获取std :: list<> :: iterator到指针的值?

时间:2010-05-02 19:19:06

标签: c++ stl iterator

如何通过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)
     }

3 个答案:

答案 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移回一个,然后擦除副本。

编辑:哦等等,你是说它不是编译?如果是这样,请参阅@ sbi的回答。但你真的需要以一种好的方式说出你的问题。你的编译错误是什么?还是在运行时失败?但是,在这种情况下,我认为你的意思是编译错误。

答案 2 :(得分:0)

我不是STL的专家,但我相信它无法编译的原因是因为迭代器是指向另一个对象的对象。换句话说,迭代器是指针的泛化。因此,要对代码进行最少的更改来执行您想要的操作,首先需要取消引用迭代器以获取它包含的值。然后你会使用'&amp;'获取其地址,然后将该地址分配给指针变量。这就是为什么ptr =&amp; * it;作品。