Great, more iterator trouble.

First we have an iterator of any value. I want to make a second iterator that starts one higher than the first one. Look-see:

for( iterator_type one ; /*...*/)
{
       for( iterator_type two = one + 1 ; /*...*/)
       {
/*...*/
        }
}

That's the gist, but I know this way doesn't work. How would I do it? I would try the ++ operator on one instead of one + 1 , but wouldn't that change the value of one?

Any help is appreciated.

if the iterator is a random_access iterator one + 1 is supported.
if not, you could write

for( iterator_type one ; /*...*/)
{
       iterator_type two = one ;
       for( ++two ; /*...*/)
       {
/*...*/
        }
}

if you want to figure out what kind of iterator it is, use std::iterator_traits<>. for example

#include <iterator>
#include <iostream>
#include <vector>
#include <list>
using namespace std ;

template< typename iterator_type > inline
void bar( iterator_type iterator, random_access_iterator_tag )
{ cout << "random access iterator!\n" ; }

template< typename iterator_type > inline
void bar( iterator_type iterator, bidirectional_iterator_tag )
{ cout << "bidirectional iterator!\n" ; }
// etc

template< typename iterator_type >
inline void foo( iterator_type iterator )
{
  bar( iterator,
   typename iterator_traits<iterator_type>::iterator_category()
   ) ;
}

int main()
{
  vector<int> vec ;
  list<int> lst ;
  cout << "vector<int>::reverse_iterator: " ; 
  foo( vec.rbegin() ) ;
  cout << "list<int>::iterator: " ; 
  foo( lst.begin() ) ;
}

Thanks again; that one was a little to simple for me to be so stuck on ^_^U

How do you know so much about iterators, anyways? You must need to use them all the time if you can so quickly come up with all the answers.

> How do you know so much about iterators, anyways? You must need to use them all the time
a c++ programmer would use iterators extensively. and so gets to be quite familiar with them.

This article has been dead for over six months. Start a new discussion instead.