C++ – Access Iterator in BOOST_FOREACH loop

boostc++foreachiterator

I have a BOOST_FOREACH loop to iterate over a list. Unfortunately, I also need to cache an iterator to a particular item.

typedef List::iterator savedIterator;

BOOST_FOREACH(Item &item, list)
{
// stuff...
  if (condition)
    savedIterator = &item; // this won't work

// do more stuff...     
}

Obviously I can do this using a list.begin()..list.end() for loop, but I've grown to like BOOST_FOREACH. Is there a way round this?

Best Solution

This is not possible, as you do not have access to an iterator pointing to the current item inside the loop.

You could fetch an iterator from the list somehow using the current items data but I don't know if this is a good idea to follow, also performance-wise.

I'd suggest you use the solution you already proposed yourself with list.begin() .. list.end(), this is in my opinion the easiest to implement and recognize.