Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a Single Pass Algorithm

Tags:

c++

iterator

stl

While i'm reading about STL iterators, this note found in https://www.sgi.com/tech/stl/Iterators.html

The most restricted sorts of iterators are Input Iterators and Output Iterators, both of which permit "single pass" algorithms but do not necessarily support "multi-pass" algorithms.

  1. What does the mean of "Single Pass Algorithms"
  2. What does the mean of above sentence
like image 509
Nayana Adassuriya Avatar asked Dec 15 '22 19:12

Nayana Adassuriya


2 Answers

Iinput-iterators are one-pass iterators i.e You can iterate over them only once. Whereas forward iterators are multi-pass.

Also, For input iterators, a == b does not imply ++a == ++b. which means algorithms on input iterators should never attempt to pass through the same iterator twice. They should be single pass algorithms.

EDITED TO GIVE MORE CLARIFICATION:-

Input iterators are single pass iterators:-

This means that they can only advance over the list a single element at a time, and once an item has been iterated, it will never be iterated again. For e.g, consider an input iterator that iterates over std::cin. It will return a character at a time, as they are ready in the input stream, but you can never “go back” to a previous character in the stream.

Forward iterators are multi-pass iterators:-

This means that you can “go back” to a previous character, but you cannot do so from the iterator object itself

forward_iterator iter = some_list.begin();
forward_iterator iter2 = iter;

item i = *iter;  // Legal, we're using a first pass

++iter;  // Legal, moving forward
--iter;  // Illegal!  It's a forward-only iterator

item i2 = *iter2;  // Legal, we're using a second pass to read an earlier item

For input iterator this would be illegal.
item i2 = *iter2;  //Illegal

Hope I am clear...

like image 139
ravi Avatar answered Dec 28 '22 05:12

ravi


I think you mean a one-pass algorithm.

One-pass algorithm: The algorithm doesn't need to access an item in the container more than once (i.e. all of the items in the container are read or written only once). Finding a certain element in an sorted array and finding n-th element in some data structures are for examples.

"Multi-pass" algorithm: The algorithms probably needs to read or write an item more than once. For these cases you have to use multiple-passes iterator, such as ForwardIterator, BidirectionalIterator, RandomAccessIterator in C++, see also Iterators on CPP Reference.

like image 40
Hannah Cheng Avatar answered Dec 28 '22 05:12

Hannah Cheng