开发者

How to access the 'previous' element in a C++ list iterator loop?

开发者 https://www.devze.com 2023-02-22 16:34 出处:网络
I\'m trying to access the previously iterated element in a loop going through all the elements of a list.

I'm trying to access the previously iterated element in a loop going through all the elements of a list.

To be more specific, my loop looks like this:

for (iter=list_object.begin(); iter!= lis开发者_C百科t_object_.end(); iter++)
  {
    function_1(*iter);
    function_2(*PREVIOUS_VALUE_IN_THE_LIST);
  }

How do I access this previous value in the list?


An easy way is to simply keep track of the previous element in the for loop, such as:

for( list_t::iterator iter=obj.begin(), prev=obj.end(); 
    iter != obj.end(); prev=iter, ++iter )
{
  function_1(*iter);
  if( prev != obj.end() )
    function_2(*prev)
}

This will work with iterators which are simply Forward, they don't need to be Bidirectional.


std::list is only bidirecitonally iterable, so you can only move the iterator one position at a time. You thus need to create a new iterator:

iter_copy = iter;
--iter;

Obviously, you are responsible for ensuring that a previous element actually exists before you decrement the iterator.

In C++0x, this functionality is neatly wrapped up in the std::prev function, which your C++ Standard Library implementation may support. If not, it looks something like this:

template <typename BidiIt>
BidiIt prev(BidiIt x, typename std::iterator_traits<BidiIt>::difference_type n=1)
{
    std::advance(x, -n);
    return x;
} 


operator-- decrements an iterator.

std::list has a Bidirectional iterator. http://www.cplusplus.com/reference/std/iterator/BidirectionalIterator/


There are two possibilities. Either --itor or std::advance(itor, -1).

0

精彩评论

暂无评论...
验证码 换一张
取 消