Getting value of std::list<>::iterator to pointer?

前端 未结 3 1693
孤独总比滥情好
孤独总比滥情好 2021-02-01 07:30

How can i loop thru a stl::List and store the value of one of the objects for use later in the function?

Particle *closestParticle;
for(list::ite         


        
相关标签:
3条回答
  • 2021-02-01 07:46

    For a list, the only way to invalidate an iterator is to erase it. So I suspect you're calling list.erase(p1) at some point in the loop. You need to make a copy of the iterator, move p1 back one, and then erase the copy.

    EDIT: Oh wait, did you mean it doesn't compile? If so, see @sbi's answer. But you really need to word your question in a good way. What is your compile error? Or does it fail at run-time? In this case, however, I believe you mean a compile error.

    0 讨论(0)
  • 2021-02-01 07:47

    Either

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

    or

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

    or

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

    or

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

    These are sorted in increasing personal preference. :)

    0 讨论(0)
  • 2021-02-01 07:50

    I'm not an expert on the STL, but I believe the reason it fails to compile is because an iterator is an object that points to another object. In other words, an iterator is a generalization of a pointer. So to do what you'd want with minimal changes to your code, you would first need to de-reference the iterator to get at the value it contains. You'd then use the '&' to get its address and would then assign that address to your pointer variable. This is why ptr=&*it; works.

    0 讨论(0)
提交回复
热议问题