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<Particle>::iterator p1 = mParticles.begin(); p1 != mParticles.end(); ++p1 )
{
// Extra stuff removed
closestParticle = p1; // fails to compile (edit from comments)
}
Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.
It is used to return an iterator pointing to the first element in the list container. It is used to return an iterator referring to the past-the-end element in the list container. Its syntax is as follows: iterator begin();
Unfortunately, there is no way to convert from an iterator directly to a pointer without dereferencing the iterator ( it[0] and &*it both dereference the iterator). As a result, the only way to convert iterators to pointers that is able to handle all valid iterators requires having access to the vector in question.
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. :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With