Iterator

This product was added to computer science because of the content, defects on the quality assurance side of the editor. This is done to bring the quality of the articles from the computer science subject area to an acceptable level. Help us to eliminate the substantive shortcomings of this article and take part you in the discussion! ( )

The term iterator comes from the field of software development and denotes a pointer to the elements of a set can be run ( such as a list ). The iterator is sometimes called in particular in the area of ​​databases and cursor.

  • 2.1 C # and other. NET languages
  • 2.2 C
  • 2.3 Java
  • 2.4 MATLAB
  • PHP 2.5
  • Python 2.6
  • Ruby 2.7

Description

An iterator is a special pointer that can be used within a program by the software developer to, for the elements in an amount that makes a list of access. Iterators operate on the basic principle of "If there is another item in the list, then post it available. "

This is thus simplified compared how a text that is a list of words reads: "If there is a next word, then read it, if not another word follows, the text is finished.. " In each iteration, referred to as Access step therefore is exactly one word of the text are available for editing.

Many of the iterators used in the programming practice set on the read access option provides mechanisms available to remove a currently read item from the list or add a new item to the list, and can be inserted or deleted words in the processing of a text.

External iterators and the iterator design pattern

An external iterator can be seen as a kind of pointer, which has two primary functions: A specific element in a set of objects referenced ( called element access ) and to show by yourself modification to the next element in the set (element traversal called ). Depending on the programming language used and the use of iterators may have additional functionality and different behavior.

The main purpose of the iterator is to allow the user access to each element in an amount, while it is isolated from the data structure of the set. This enables the crowd to manage the items in every possible way, while facing the user behaves as if it were a simple sequence or a list. An iterator is designed in close coordination with its container class, so their amount. Typically, the container class the functions that are used for creating iterators. (Also called a loop counter) is a counter in a loop is sometimes referred to as loop iterator. It should be noted that such a counter element reflects only the traversal functionality and not the element access functionality.

Generators

One way to implement iterators to create a special function, which is known as the generator. This, instead redeliver an item at a time, return multiple items in multiple steps to the user. Most iterators can be mapped in a natural, intuitive way by generators. Since generators maintain their local state between function calls, they are highly suitable for implementation of complex state -based iterators as so-called Binärbaumtraversierer. As an example, a generator above, which returns numbers in a Fibonacci sequence using the Python command yield:

Def fibonacci ( ):       a, b = 0, 1       while True:           yield a           A, B = b a b     for number in fibonacci ( ): # Use the generator as an iterator       print (number) Implicit iterators

Several object -oriented languages ​​such as Perl, Python, C #, Ruby and newer Java and Delphi versions in an intrinsic way to iterate through elements available, without using an explicit iterator. However, this can also be present, but in the code of the programming is not available if this should be the case.

Implicit iterators often manifest themselves through the foreach command or its equivalent, as below shows Python example:

For value in iterable:      print (value) Sometimes iterators also be generated directly from the object of the data collection as below Ruby example shows:

Iterable.each do | value |    puts value end This Iterationsstil is also called internal iteration, since its code runs entirely in the context of the iterated object to. Therefore, it can control all aspects of the iteration, the respective user, respectively programmer only provides the operation for each iteration is available by using an anonymous subroutine.

Languages ​​that support so-called list comprehensions or similar constructs, the implicit iterators operate analogously to Python also during the creation of the result list:

Names = [ person.name for person in roster if person.male ] Sometimes the implicit, hidden nature is only partially available. The C programming language, the for_each function via function templates are available, this allows the implicit iteration.

The contrast to index

Iterator stands in contrast to an index or key:

  • Can directly access the corresponding element without knowing the data structure itself over an iterator. For an index, you always need index and data structure.
  • An iterator is only valid for exactly one data structure. An index can be applied to other data structures.
  • Iterators can not serialize. You will need to be converted first to an index.

The ability of a container of self - modification while iterating through its elements, has proven in modern, object-oriented programming languages ​​as important. The inter-relationships between individual objects and the effects of their operations are no longer clearly in such languages ​​. To solve this problem, iterators are used.

Iterators in different programming languages

C # and other. NET languages

Iterators. NET Framework are called enumerators, and represented by the IEnumerator interface. IEnumerator provides a function called MoveNext () available, which is in each case to the next element of the set and indicates when the end is reached, and a property named Current to get the value of the current element. Furthermore, an optional reset function offered to return to the beginning. The enumerator as the initialization returns a special value that marks the beginning; for this reason it is necessary to run after initialization MoveNext ().

Enumerators are typically returned by a GetEnumerator ( ) function, which is an object belonging that implements the IEnumerable interface. The foreach command in C #, however, operates on each such function, even if this is not from an object that implements the IEnumerable interface. The following example shows a simple use of iterators in C # 2.0:

/ / Explicit Version IEnumerator iter = list.GetEnumerator (); while ( iter.MoveNext ())      Console.WriteLine ( iter.Current );   / / Implicit version foreach ( MyType value in list)      Console.WriteLine ( value); C # 2.0 also supports generators: a function which returns a IEnumerator or IEnumerable as, but the yield return command used here, is automatically converted by the compiler into a new class that implements the appropriate interface.

C

The programming language C iterators is on a grand scale and is about the C standard library iterators of different types, such as so-called forward iterators, bidirectional iterators and random access iterators available. Each of the standard container classes has iterator. The syntax of the Standarditeratoren was based on the pointer arithmetic of C. The operators * and -> are used for referencing the elements. Other operators such as are used to navigate through the items.

Iterators are usually used in pairs. Of a iterator is the current iteration, and the other is the end of the iteration. The iterators are generated by the corresponding container class through the use of standard functions begin () and end (). The iterator returned by begin ( ) points to the first element, while the iterator is zurückgegliefert end (), to a specific value shows that references an element. If an iterator is positioned after the last element, this returns the special value of end (). The following example illustrates a typical use of an iterator in C :

Container Type C; / / Any default container type, such as std :: list   for ( container :: const_iterator type constit = C.begin ();! constit = C.end (); constit ) {      std :: cout << * constit << ' \ n'; } There are many different iterator types with slightly from each other deviant behavior. Not every iterator supports any type of container. However, it is possible for programmers to define their own iterator types by deriving a class from the template std :: iterator. The Iteratorsicherheit is defined separately for the different types. The implicit iteration is partially available in C and is used by the functions std :: for_each (), std :: copy () and std :: accumulate () provided. Iterators, however, always require an explicit object to its initialization, usually those that are returned by begin () and end (). Once this has been performed, the iteration is done implicit manner without iterator further use. The example below shows the use of for_each:

Container Type C; / / An arbitrary standard container type of each element ItemType   has ProcessItem void (const ItemType & I) / / function that access to each element {     std :: cout << I << ' \ n'; }   std :: for_each ( C.begin () C.end () ProcessItem ); / / A for-each iteration loop The same can be achieved through the use of std :: copy and std :: ostream_iterator:

Std :: copy ( C.begin () C.end (), std :: ostream_iterator (std :: cout, "\ n ")); A limitation of this technique is that it does not allow the trunk to be declared inline. Moreover, this requires a function pointer, which are declared elsewhere and must be passed as a parameter. This can be partially compensated by the use of libraries like Boost and the use of lambda that are needed in order to generate function objects related with infix syntax. Because this functionality is available only through external libraries must various workarounds, also called workarounds are used.

Java

The interface java.util.Iterator, which was introduced in Java JDK 1.2, allows iterating container classes. Each iterator provides functions called next (), hasNext (), as well as an optional feature called remove () are available. Iterators are usually generated by a feature called iterator ( ) which is provided by the corresponding thereto container class. An iterator is as initialization value returns a special value that marks the beginning. For this reason, it is necessary after the initialization next () to perform, with which the first element is returned. The function hasNext () is used to find out when the last item was returned. The following example shows a simple use of iterators in Java:

Iterator iter = list.iterator (); / / Iterator iter = list.iterator (); in J2SE 5.0 while ( iter.hasNext ()) {      System.out.println ( iter.next ()); } For collections that support it, removed the optional function remove () the last element that was accessed. Most other modifications of this nature are uncertain. In addition, java.util.List has an iterator called ListIterator, which provides a similar interface, the forward and backward iteration allowed and returns the index of the current element and can insert the element at a given position.

With J2SE 5.0, the interface Iterable was introduced, which is an extended for loop within the meaning of foreach. Iterable defines the function iterator ( ), which returns an iterator. Using the enhanced for loop, the previous example can be written in the following way:

For ( MyType obj: list ) {      System.out.println (obj ); } MATLAB

MATLAB supports external and internal iterators. In the case of an external iteration in which the user is required to provide the next element, several elements can be defined and then be gone through with a for loop, as the following example shows:

% Definition of arrays of integer myArray = [ 1,3,5,7,11,13 ];   for n = myArray     % ... Do something with n ...     disp ( n ) % Integer output to the command line end In the case of an internal iteration the user can perform an operation passed to the iterator to access each element in an array. Many native MATLAB operators and functions are overloaded to a corresponding output array to obtain as an implicit return value. Furthermore, the functions can arrayfun and cellfun for Custom Operations on native and so-called cell arrays are used.

Function simpleFun % Definition of arrays of integer myArray = [ 1,3,5,7,11,13 ];   % Perform Custom operation for each element myNewArray arrayfun = ( @ ( a) myCustomFun ( a), myArray );   % % Array output to the command line myNewArray   function outScalar = myCustomFun ( inScalar ) % Multiply with 2 outScalar = 2 * inScalar; Alternatively, it may be desirable to abstract the storage mechanisms of the array of programming, by providing a custom, object-oriented implementation of the Iteratorentwurfsmusters is provided. Such an implementation which supports the external iteration is offered in the MATLAB Central File Exchange item. This design pattern is written according to the new Klassendefnitionssyntax which the MATLAB Version 7.6 ( R2008a ) has been introduced. Furthermore, a one-dimensional cell array implementation of the List Abstract Data Type containing make a heterogeneous storage of each data type. It provides the functionality to display a list with hasNext (), next () and reset ( ) processed in a while loop.

PHP

With PHP4 a foreach construct was introduced which had a similar design as in Perl and many other programming languages. This construct allows an easy way to iterate over arrays. The foreach command works only with arrays in PHP4 and will raise an error is when trying to use it on a different data type or an uninitialized variable. In PHP5 the foreach command to iterate over all public members is allowed. The following example shows two different ways of writing, the second is a useful extension to the first notation:

example B $ value)      echo " ($ key) $ value \ n";? > In example A is an array which is represented by array_expression is iterated. Each time through the loop, the value of the array element is assigned to $ value and pushed the internal pointer of the array by one to the front. So the next time through the loop, the next array element is returned. The example B has the same functionality as the example of A. In addition, the index of the element in each loop of the variable $ key is assigned.

In PHP5 the Iteratorschnittstelle is predefined objects can be modified in order to handle the iteration.

var = $ array;         }       }         public function rewind () {         echo " rewinding \ n";         reset ($ this-> var);       }         public function current () {         $ var = current ($ this-> var);         echo " current: $ var \ n";         return $ var;       }         public function key () {         $ var = key ($ this-> var);         echo " key: $ var \ n";         return $ var;       }         public function next () {         $ var = next ( $ this -> var);         echo "next $ var \ n";         return $ var;       }         public function valid () {         $ var = $ this-> current () == false! ;         echo "valid: { $ var } \ n";         return $ var;       }    }? > These functions are all used in a complete foreach ( $ obj AS $ key => $ value) sequence. The iterator methods are executed in the following order:

1 rewind ()    While 2 valid ()       {            2.1 current () in $ value            2.3 key () in $ key            2.4 next ()       } Python

Iterators in Python are a fundamental part of the language, but they are often used implicitly and thus hidden in invisible voice commands. Such commands are, for example, for ( foreach ) in so-called list comprehensions and generator expressions in. All sequential basic types as well as many classes of the standard library in Python support iterations. The following example shows a typical iteration over a sequence:

For value in sequence:       print (value) Python dictionaries, a form of Associative array allows to iterate if the so-called dictionary keys are returned directly above him. It can also be on the items of a function to iterate dictionary, where it returns the values ​​of the following example, according to key and value:

For key in dictionary:      value = dictionary [ key]      print ( key, value ) for key, value in dictionary.items ():      print ( key, value ) But iterators in Python can also be explicitly defined and used. For any iterable sequence types or any iterable class the built- iter () function available to an iterator object is to be generated. The iterator can be used with functions next ( ) or __ are next__ () to navigate to the next item. If the end of the crowd reached a StopIteration is raised error. The following example shows an equivalent implementation of explicit iterators:

It = iter ( sequence) while True:      try:          value = it.next ()      except StopIteration:          break      print (value) Each custom class can support the Standarditeration when a _iter__ () function has been defined which generates an iterator, the iterator must then next__ __ () function to define which returns the next element. The Python generators implement this iteration.

Ruby

The implementation of iterators in Ruby is different from most other programming languages ​​: all iterations go to the idea of ​​so-called callback closures percolating an container methods. In this way Ruby implemented not only a basic functionality of iterators, but makes many Iteratorentwurfsmuster from such as so-called function mapping, filters and so-called reducing.

Ruby also supports the more an alternative syntax for each basis function to iterate:

( 0 .. 42) each do |. N |   puts n end And ... ...

For n in 0 .. 42   puts n end or even shorter

42.times do | n |   puts n end References

309773
de