# incrementing list iterators

• 04-25-2007
Lima
incrementing list iterators
I'm having a little problem here...

If I have this:
int N = 5;
list <type> newlist;
list <type>::iterator it = newlist.begin();
it = it + N;

on the bold line above, it doesn't let me do it, doesn't even compile.

How can I increment a list iterator N units forward?
• 04-25-2007
ZuK
like this
Code:

```#include<iterator> #include<list> #include<iostream> using namespace std; int main() {     list<int> l;     l.insert(l.end(), 1);     l.insert(l.end(), 2);     l.insert(l.end(), 3);     l.insert(l.end(), 4);     list<int>::iterator itr = l.begin();     advance(itr,2);     cout << *itr << endl; }```
Kurt
• 04-25-2007
Lima
yeah it works now, thanks very much ^^
• 04-25-2007
jk1998
Could someone explain why it= it + N doesn't work? It works with this

Code:

```vector<int> the_vector;   vector<int>::iterator the_iterator;   for( int i=0; i < 10; i++ )     the_vector.push_back(i);   int total = 0;   the_iterator = the_vector.begin();   while( the_iterator != the_vector.end() ) {     total += *the_iterator;     the_iterator++;   }   cout << "Total=" << total << endl;```
• 04-25-2007
Lima
Quote:

Originally Posted by jk1998
Could someone explain why it= it + N doesn't work? It works with this

Code:

```vector<int> the_vector;   vector<int>::iterator the_iterator;   for( int i=0; i < 10; i++ )     the_vector.push_back(i);   int total = 0;   the_iterator = the_vector.begin();   while( the_iterator != the_vector.end() ) {     total += *the_iterator;     the_iterator++;   }   cout << "Total=" << total << endl;```

you are working with vectores there not lists
• 04-25-2007
laserlight
List iterators are bidirectional iterators, not random access iterators. Consequently, you can do ++iter, iter++, --iter, and iter-- with list iterators, but not iter += n, iter + n, iter -= n, or iter - n. advance() in this case would just apply ++iter twice to simulate iter + 2.
• 04-25-2007
jk1998
Thanks.
• 04-25-2007
Daved
Note that technically it + N could be allowed in that it could just do the same thing that advance does. It was purposefully left out because that operation can be slow. If you find yourself using advance with lists often, then you might want to reconsider whether a list is the appropriate container for your needs.