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

One*_*ake 17 c++ iterator stl

我如何循环通过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)
     }
Run Code Online (Sandbox Code Playgroud)

sbi*_*sbi 55

Particle *closestParticle;
for(list<Particle>::iterator it=mParticles.begin(); it!=mParticles.end(); ++it)
    {
      // Extra stuff removed
            closestParticle = &*it;
    }
Run Code Online (Sandbox Code Playgroud)

要么

list<Particle>::iterator closestParticle;
for(list<Particle>::iterator it=mParticles.begin(); it!=mParticles.end(); ++it )
    {
      // Extra stuff removed
            closestParticle = it;
    }
Run Code Online (Sandbox Code Playgroud)

要么

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();
}
Run Code Online (Sandbox Code Playgroud)

要么

template< typename It > 
inline It findClosestParticle(It begin, It end)
{
    while(begin != end )
        {
          // Extra stuff removed
               return begin;
          ++begin;
        }
    return end;
}
Run Code Online (Sandbox Code Playgroud)

这些按照个人喜好逐渐增加. :)

  • @Onedayitwillmake:`*it` __derferences__迭代器并将__reference__返回给对象.然后`&`获取该对象的__address__.这是否足以解释它还是应该让我们中的一个人详细说明? (5认同)
  • 向下滚动实际上是一种愉快的体验.+1 (4认同)
  • 很好的抓住.我个人会选择#2作为我的首选.我对#3和#4感到困惑.好像你过早地回来了. (3认同)