tags:

views:

170

answers:

2

I'd like get far next value for STL list iterator but it doesn't implement operator+, vector has it though. Why and how can I get the value where I want?

I think I can do that if I call operator++ several times, but isn't that a little bit dirty?

What I want to do is the following:

list<int> l;
...omitted...
list<int>::iterator itr = l.begin() + 3; // but, list iterator does not have
                                         // operator+

What is the best solution for what I want?

+26  A: 

You want to use std::advance:

list<int>::iterator itr = l.begin();
std::advance(itr, 3);

advance will use operator+ and complete in constant time if the iterator is random access while it will loop on operator++ and complete in linear time if the iterator is not random access.

The reason for this is to give you control over complexity requirements. If you care about the complexity of your operation you use operator+ and get constant time but only compiles with random access iterators. If you don't care about the complexity you use std::advance which will always work but the complexity will vary based on the iterator.

R Samuel Klatchko
+1 simple, clear and thorough.
wilhelmtell
+11  A: 

You can also use boost::next (and prior).

list<int>::iterator itr = boost::next(l.begin(), 3);

Rationale: std::advance is awkward to use (it works by side-effect, not by returning a copy).

UncleBens
That's good to know. I always wondered why `std::advance` worked by side-effect instead of functionally.
R Samuel Klatchko
@RSam: I have always assumed it is because `std::advance` is meant to mimic ++itr or operator+=, as appropriate. Iterator algorithms are generally written in those terms, so wrapping them makes the most sense.
Dennis Zickefoose