You can use std::distance and std::advance.
Additionally you can check the iterator-traits and specialize for bidirectional iterators.
[cpp]//Template for iterator
//General approach using std::distance and std::advance
template <typename iterator, typename traits=iterator_traits<iterator>::iterator_category>
//Function that uses recursion to print out a range of values given by two iterators to a ostream in reverse.
void printReversed(const iterator min,iterator max,ostream &out)
{
//base case if min is equal to the max iterator.
if(min==max)
{
return;
}
//next max = max - 1
max=std::advance(min, std::distance(min, max) - 1);
out<<*max;
//Asks the magical Recursion Genie to print out the rest of the list.
printReversed(min,max,out);
}
//Specialization for random access iterators
template <typename iterator>
template<>
void printReversed<iterator, std::random_access_iterator_tag>(const iterator min,const iterator max,ostream &out)
{
//Random access iterators are also bidirectional
printReversed<iterator, std::bidirectional_iterator_tag>(min,max,out);
}
//Specialization for bidirectional iterators
template <typename iterator>
template<>
void printReversed<iterator, std::bidirectional_iterator_tag>(const iterator min,iterator max,ostream &out)
{
//base case if min is equal to the max iterator.
if(min==max)
{
return;
}
--max;
out<<*max;
//Asks the magical Recursion Genie to print out the rest of the list.
printReversed(min,max,out);
}[/cpp]
Sorry, you need to Log In to post a reply to this thread.