How to access the 'previous' element in a C++ list iterator loop?
Solution 1
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;
}
Solution 2
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.
Solution 3
operator-- decrements an iterator.
std::list has a Bidirectional iterator. http://www.cplusplus.com/reference/std/iterator/BidirectionalIterator/
Solution 4
There are two possibilities. Either --itor
or std::advance(itor, -1)
.
Related videos on Youtube
R.J.
Updated on April 08, 2020Comments
-
R.J. about 4 years
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!= list_object_.end(); iter++) { function_1(*iter); function_2(*PREVIOUS_VALUE_IN_THE_LIST); }
How do I access this previous value in the list?
-
Bo Persson about 13 yearsJust watch out the first round through the loop!
-
-
nirvanaswap about 8 yearsWhat a thoughtful answer. Covered the base case without me even realizing it!