Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell advance() to use += operator on input iterators if they aren't random access

Tags:

c++

iterator

Consider an input iterator like join_iterator: it iterates over the concatenation of other ranges. Calling ++i repeatedly can be much slower than a simple i += n.

Nevertheless, most C++ code that requires advancing an iterator by an arbitrary amount uses std::advance, which automatically resorts to calling ++i when the iterator isn't random-access.

(Sadly, most people use std::advance(i, n) instead of using std::advance; advance(i, n), so I can't just supply advance for my iterator and rely on ADL.)

On the other hand, I can't use + or += because input iterators don't have to implement them.

So the question is: how would I go about supporting such a scenario, when:

  • Implementing such an iterator?

  • Using an input iterator which might have an optimized operator +=?

(Note that advance and + isn't the only scenario in which this matters -- distance and - has the same problem.)

like image 529
user541686 Avatar asked May 21 '13 06:05

user541686


People also ask

What is an STL iterator?

An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container.

What is c++ iterator?

An iterator is an object that can iterate over elements in a C++ Standard Library container and provide access to individual elements.

What are three main kinds of iterators?

There are three main kinds of input iterators: ordinary pointers, container iterators, and input streams iterators.

What are input iterators?

Input iterators are iterators that can be used in sequential input operations, where each value pointed by the iterator is read only once and then the iterator is incremented. All forward, bidirectional and random-access iterators are also valid input iterators.


1 Answers

According to C++11 §24.4.4,

Since only random access iterators provide + and - operators, the library provides two function templates advance and distance. These function templates use + and - for random access iterators (and are, therefore, constant time for them); for input, forward and bidirectional iterators they use ++ to provide linear time implementations.

You should only have to define + and -, and specify std::random_access_iterator_tag. There is no need to specialize or overload std::advance.

like image 119
Potatoswatter Avatar answered Oct 22 '22 09:10

Potatoswatter