Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why only random-access-iterator implements operator+ in C++?

Tags:

c++

iterator

stl

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?

like image 233
Hongseok Yoon Avatar asked May 13 '10 18:05

Hongseok Yoon


1 Answers

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 this 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.

like image 173
R Samuel Klatchko Avatar answered Nov 16 '22 02:11

R Samuel Klatchko