Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

iterator

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!= list_object_.end(); iter++)
  {
    function_1(*iter);
    function_2(*PREVIOUS_VALUE_IN_THE_LIST);
  }

How do I access this previous value in the list?

like image 852
R.J. Avatar asked Apr 07 '11 19:04

R.J.


People also ask

How do I get the iterator to the last element in a list?

The list::end() is a built-in function in C++ STL which is used to get an iterator to past the last element. By past the last element it is meant that the iterator returned by the end() function return an iterator to an element which follows the last element in the list container.

How do you find the iterator element?

Obtain an iterator to the start of the collection by calling the collection's iterator( ) method. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. Within the loop, obtain each element by calling next( ).

What is past-the-end iterator?

std::vector::end Returns an iterator referring to the past-the-end element in the vector container. The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.

Is prev a keyword in C++?

Well, the answer is yes.


1 Answers

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.

like image 167
edA-qa mort-ora-y Avatar answered Oct 23 '22 04:10

edA-qa mort-ora-y