c++ - 将 std::list<>::iterator 的值指向指针?

标签 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)
     }

最佳答案

要么

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;
}

这些是按照个人喜好的增加排序的。 :)

关于c++ - 将 std::list<>::iterator 的值指向指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2754650/

相关文章:

c++ - 如何像 c 数组一样初始化 'const std::vector<T>'

STL - STL map::find 函数在没有相等运算符的情况下如何工作?

c++ - const_iterator 到迭代器 C++ 错误

python - 所有迭代器都会缓存吗? csv.Reader 怎么样?

javascript - 从 Qt 中读取带有 "evaluateJavaScript"的 javascript 函数的返回值

c++ - native Nuget 包安装在 VS 中,但没有为 C++( native )项目添加引用

c++ - 使用整数运算的平滑算法

c++ - 带有 WH_KEYBOARD 的 SetWindowsHookEx 卡在循环/队列中

c++ - 如何为 std::vector<std::vector<bool>> 编写哈希函数

c++ - map C++ 上的 BAD_ACCES 迭代器