What is a Single Pass Algorithm

给你一囗甜甜゛ 提交于 2019-12-23 03:36:11

问题


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

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/26322007/what-is-a-single-pass-algorithm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!