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?
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.
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( ).
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.
Well, the answer is yes.
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.
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