I was trying to access the last element of the map using an iterator using below approach
std:: iterator last_butone_elem = someMap.end();
for (iter = someMap.begin(); iter != someMap.end(); ++iter) {
// do something for all iterations
if (iter = --last_butone_elem) {
++iter;
// do something for all but only for the last iteration
}
Problem I am facing: The below approach is working fine for odd number of map elements but not for even number of elements in map.I mean its not entering inside if condition for odd number of elements of my map.
I do not have any idea , why it is behaving like this. Could some one please help me resolving this problem?
> I do not have any idea , why it is behaving like this.
The iterator last_butone_elem is being decremented each time through the loop.
To get to the last element, decrement it just once, before the loop starts.
1 2 3 4 5 6 7 8 9 10 11 12
template < typename ORDERED_MAP > auto last_element_of( ORDERED_MAP& map )
{
auto iter = map.end() ;
return map.empty() ? iter : --iter ;
}
template < typename ORDERED_MAP, typename FN >
void for_all_but_last( ORDERED_MAP& map, FN fn )
{
constauto iter_last = last_element_of(map) ;
for( auto iter = map.begin() ; iter != iter_last ; ++iter ) fn(*iter) ;
}
@JLBorges and @gunnerfunner
I am not using c++11 compiler. if i not wrong Auto keyword is specific to c++11.
May be my question is not clear.
I need to print all the elements in my map to console in one format and only the last element in another format. So with in the iterator I wanted to modify the last element using "if" condition (checking for last before element ) and print my last element in a different format to the console.
With the solutions proposed above , either I can iterate through only till my last but one element or my map elements in reverse order . But my intention is different(mentioned in above paragraph).