All Topics  
Iterator

 

   Email Print
   Bookmark   Link






 

Iterator



 
 
In computer science
Computer science

Computer science is the study of the theoretical foundations of information and computation, and of practical techniques for their implementation and application in computer systems....
, an iterator is an object that allows a programmer to traverse through all the elements of a collection
Collection (computing)

In computer science, a collection is a grouping of some variable number of data items that have some shared significance to the problem being solved and need to be operated upon together in some controlled fashion....
, regardless of its specific implementation. An iterator is sometimes called a cursor
Cursor (databases)

In database packages, a cursor comprises a control structure for the successive wikt:traverse of database record in a result set.Database programmers use cursors for processing individual rows returned by the database system for a query....
, especially within the context of a database
Database

A database is a structured collection of records or data that is stored in a computer system. The structure is achieved by organizing the data according to a database model....
.

Description
An iterator may be thought of as a type of pointer which has two primary operations: referencing one particular element in the object collection (called element access), and modifying itself so it points to the next element (called element traversal).






Discussion
Ask a question about 'Iterator'
Start a new discussion about 'Iterator'
Answer questions from other users
Full Discussion Forum



Encyclopedia


In computer science
Computer science

Computer science is the study of the theoretical foundations of information and computation, and of practical techniques for their implementation and application in computer systems....
, an iterator is an object that allows a programmer to traverse through all the elements of a collection
Collection (computing)

In computer science, a collection is a grouping of some variable number of data items that have some shared significance to the problem being solved and need to be operated upon together in some controlled fashion....
, regardless of its specific implementation. An iterator is sometimes called a cursor
Cursor (databases)

In database packages, a cursor comprises a control structure for the successive wikt:traverse of database record in a result set.Database programmers use cursors for processing individual rows returned by the database system for a query....
, especially within the context of a database
Database

A database is a structured collection of records or data that is stored in a computer system. The structure is achieved by organizing the data according to a database model....
.

Description


An iterator may be thought of as a type of pointer which has two primary operations: referencing one particular element in the object collection (called element access), and modifying itself so it points to the next element (called element traversal). There must also be a way to create an iterator so it points to some first element as well as some way to determine when the iterator has exhausted all of the elements in the container. Depending on the language and intended use, iterators may also provide additional operations or exhibit different behaviors.

The primary purpose of an iterator is to allow a user to process every element of a container while isolating the user from the internal structure of the container. This allows the container to store elements in any manner it wishes while allowing the user to treat it as if it were a simple sequence or list. An iterator class is usually designed in tight coordination with the corresponding container class. Usually the container provides the methods for creating iterators.

Note that a loop counter
Loop counter

In software engineering, a loop counter is the term often used to refer to the variable that controls the iterations of a For loop . It is so named because most uses of this construct result in the variable taking on a range of integer values in some orderly sequence ...
 is sometimes also referred to as a loop iterator. A loop counter
Loop counter

In software engineering, a loop counter is the term often used to refer to the variable that controls the iterations of a For loop . It is so named because most uses of this construct result in the variable taking on a range of integer values in some orderly sequence ...
, however, only provides the traversal functionality and not the element access functionality.

Contrasting with indexing


In procedural languages it is common to use index
Index (information technology)

In computer science, an index can be:# an integer which identifies an array element# a pointer data element.# a data structure that enables sublinear-time lookup...
ing based on a loop counter
Loop counter

In software engineering, a loop counter is the term often used to refer to the variable that controls the iterations of a For loop . It is so named because most uses of this construct result in the variable taking on a range of integer values in some orderly sequence ...
 to loop through all the elements in a sequence such as an array. Although indexing may also be used with some object-oriented containers, the use of iterators may have some advantages:

  • Counting loops are not suitable to all data structures, in particular to data structures with no or slow random access
    Random access

    In computer science, random access is the ability to access an arbitrary element of a sequence in equal time. The opposite is sequential access, where a remote element takes longer time to access....
    , like lists
    List (computing)

    In computer science, a list is an ordered Multiset of entity/items.In the context of object-oriented programming languages, a list is defined as an instance of an abstract data type , formalizing the concept of an order theoryed Collection class of entity....
     or trees.


  • Iterators can provide a consistent way to iterate on data structures of all kinds, and therefore make the code more readable, reusable, and less sensitive to a change in the data structure.


  • An iterator can enforce additional restrictions on access, such as ensuring that elements can not be skipped or that a previously visited element can not be accessed a second time.


  • An iterator may allow the container object to be modified without invalidating the iterator. For instance, once an iterator has advanced beyond the first element it may be possible to insert additional elements into the beginning of the container with predictable results. With indexing this is problematic since the index numbers must change.


The ability of a container to be modified while iterating through its elements has become necessary in modern object-oriented programming, where the interrelationships between objects and the effects of operations may not be obvious. By using an iterator one is isolated from these sorts of consequences.

Implicit iterators


Some object-oriented languages such as Perl
Perl

In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
, Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
, C#, Ruby
Ruby (programming language)

Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features....
 and later versions of Java
Java (programming language)

Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
 and Delphi
Object Pascal

Object Pascal refers to a branch of Object-oriented programming derivatives of Pascal , mostly known as the primary programming language of CodeGear Delphi....
 provide an intrinsic way of iterating through the elements of a container object without the introduction of an explicit iterator object. An actual iterator object may exist in reality, but if it does it is not exposed within the source code of the language.

Implicit iterators are often manifested by a "foreach
Foreach

For each is a computer language idiom for traversing items in a Collection class. Foreach is usually used in place of a standard for loop statement ....
" statement (or equivalent), such as in the following Python example:

for value in iterable: print value

Or other times they may be created by the collection object itself, as in this Ruby example:

iterable.each do |value| puts value end

This iteration style is sometimes called "internal iteration" due to fully executing within the context of the iterable object (which controls all aspects of iteration), and the programmer only provides the operation to execute at each step (using an anonymous function
Anonymous function

In computing, an anonymous function is a function defined, and possibly called, without being bound to a name. In lambda calculus, all functions are anonymous....
).

Languages which support list comprehension
List comprehension

A list comprehension is a Syntax of programming languages construct available in some programming languages for creating a list based on existing lists....
s or similar constructs may also make use of implicit iterators during the construction of the result list, as in Python:

names = [person.name for person in roster if person.male]

Sometimes the implicit hidden nature is only partial. The C++
C++

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
 language has a few function templates, such as for_each, that allow for similar implicit iteration. However they still require explicit iterator objects as their initial input. But once initialized the subsequent iteration happens implicitly without the continued use of any exposed iterator object.

Generators


One way of implementing iterators is using a special kind of subroutine
Subroutine

In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code....
, known as a generator, that can yield values to its caller multiple times (instead of returning just once). Most iterators are naturally expressible as generators, but because generators preserve their local state between invocations, they're particularly well-suited for complicated, stateful iterators, such as tree traversers
Tree traversal

In computer science, tree-traversal refers to the process of visiting each node in a tree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodes are visited....
. An example of a generator returning the Fibonacci number
Fibonacci number

In mathematics, the Fibonacci numbers are a sequence of numbers named after Leonardo of Pisa, known as Fibonacci . Fibonacci's 1202 book Liber Abaci introduced the sequence to Western European mathematics, although the sequence had been previously described in Indian mathematics....
s using Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
's yield statement can be seen below.

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

Iterators in different programming languages


C++


The C++
C++

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
 language makes wide use of iterators in its Standard Template Library
Standard Template Library

The Standard Template Library is a Library partially included in the C++ C++ standard library. It provides Container s, iterators, algorithms, and Function objects....
, which provides several different kinds of iterators, including forward iterators, bidirectional iterators, and random access iterators. All of the standard container template types provide a rich and consistent set of iterator types. The syntax of standard iterators is designed to resemble that of ordinary C
C (programming language)

C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
 pointer arithmetic, where the * and -> operators are used to reference the element to which the iterator points, and pointer arithmetic operators like ++ are used to advance the iterator to the next element.

Iterators are usually used in pairs, where one is used for the actual iteration and the second serves to mark the end of the collection. The iterators are created by the corresponding container class using standard methods such as begin and end. The iterator returned by begin points to the first element, while the iterator returned by end is a special value that does not reference any element.

When an iterator is advanced beyond the last element it is by definition equal to the special end iterator value. The following example shows a typical use of an iterator.

ContainerType C; // Any standard container type, like stdlist //for (ContainerTypeiterator it = C.begin; it != C.end; ++it) //(if you need to modify elements) for (ContainerTypeconst_iterator it = C.begin; it != C.end; ++it)

There are many varieties of iterators each with slightly different behavior, including: forward, reverse, and bidirectional iterators; random-access iterators; input and output iterators; and const iterators (which protect the container or its elements from modification). However not every type of container supports every type of iterator. It is possible for users to create their own iterator types by deriving subclasses from the standard stditerator class template.

Iterator safety is defined separately for the different types of standard containers, in some cases the iterator is very permissive in allowing the container to change while iterating.

Implicit iteration is also partially supported by C++ through the use of standard function templates, such as and . When used they must be initialized with existing iterators, usually begin and end, that define the range over which iteration occurs. But no explicit iterator object is subsequently exposed as the iteration proceeds. This example shows the use of for_each.

ContainerType C; // Any standard container type of ItemType elements void ProcessItem( const ItemType& I ) // Function which will process each item of the collection

stdfor_each( C.begin, C.end, ProcessItem ); // A for-each iteration loop

A limitation is that this technique does not allow the body of the for-each loop to be declared inline, requiring a function pointer
Function pointer

A function pointer is a type of pointer in C , C++, D programming language, and other C-like programming languages. When Dereference operator, a function pointer invokes a subroutine, passing it zero or more arguments just like a normal function....
 or function object
Function object

A function object, also called a functor, functional or functionoid, is a computer programming construct allowing an object to be invoked or called as if it were an ordinary function , usually with the same syntax....
 to be declared elsewhere and passed as an argument. This can be partially compensated for by using a library such as Boost
Boost library

The Boost C++ Libraries are a collection of peer-reviewed, open source Library that extend the functionality of C++. Most of the libraries are licensed under the Boost Software License, designed to allow Boost to be used with both open and closed source projects....
 and using lambda to implicitly generate function objects with familiar infix operator syntax. Due to it only being a library, however, certain operations have to be done via workarounds.

C# and other .NET languages


Iterators in the .NET Framework
.NET Framework

The Microsoft .NET Framework is a software framework that is available with several Microsoft Windows operating systems. It includes a large Library of coded solutions to prevent common programming problems and a virtual machine that manages the execution of programs written specifically for the Software framework....
 are called "enumerators" and represented by the IEnumerator interface. IEnumerator provides a MoveNext method, which advances to the next element and indicates whether the end of the collection has been reached; a Current property, to obtain the value of the element currently being pointed at; and an optional Reset method, to rewind the enumerator back to its initial position. The enumerator initially points to a special value before the first element, so a call to MoveNext is required to begin iterating.

Enumerators are typically obtained by calling the GetEnumerator method of an object implementing the IEnumerable interface. Container classes typically implement this interface. However, the foreach
Foreach

For each is a computer language idiom for traversing items in a Collection class. Foreach is usually used in place of a standard for loop statement ....
 statement in C# can operate on any object providing such a method, even if it doesn't implement IEnumerable. Both interfaces were expanded into generic
Generic programming

Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters and was pioneered by Ada which appeared in 1983....
 versions in .NET 2.0
.NET Framework

The Microsoft .NET Framework is a software framework that is available with several Microsoft Windows operating systems. It includes a large Library of coded solutions to prevent common programming problems and a virtual machine that manages the execution of programs written specifically for the Software framework....
.

The following 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
Iterator

In computer science, an iterator is an object that allows a programmer to traverse through all the elements of a Collection , regardless of its specific implementation....
: a method which is declared as returning IEnumerator (or IEnumerable), but uses the "yield return" statement to produce a sequence of elements instead of returning an object instance, will be transformed by the compiler into a new class implementing the appropriate interface.

Java


Introduced in the Java
Java (programming language)

Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
 JDK 1.2 release, the interface allows the iteration of container classes. Each Iterator provides a and method, and may optionally support a method. Iterators are created by the corresponding container class, typically by a method named iterator.

The next method advances the iterator and returns the value pointed to by the iterator. When first created, an iterator points to a special value before the first element, so that the first element is obtained upon the first call to next. To determine when all the elements in the container have been visited the hasNext test method is used. The following example shows a simple use of iterators:

Iterator iter = list.iterator; //Iterator iter = list.iterator; in J2SE 5.0 while (iter.hasNext) System.out.println(iter.next);

For collection types which support it, the remove method of the iterator removes the most recently visited element from the container. Most other types of modification to the container while iterating are unsafe.

Additionally, for there is a with a similar API but that allows forward and backward iteration, provides its current index in the list and allows setting of the list element at its position.

The J2SE
Java Platform, Standard Edition

Java Platform, Standard Edition or Java SE is a widely used Platform for programming in the Java language. It is the Java Platform used to deploy porting Application software for general use....
 5.0 release of Java introduced the interface to support an enhanced for (foreach
Foreach

For each is a computer language idiom for traversing items in a Collection class. Foreach is usually used in place of a standard for loop statement ....
) loop for iterating over collections and arrays. Iterable defines the method that returns an Iterator. Using the enhanced for loop, the preceding example can be rewritten as

for (MyType obj : list) System.out.print(obj);

Ruby


Ruby implements iterators quite differently; all iterations are done by means of passing callback closures to container methods - this way Ruby not only implements basic iteration but also several patterns of iteration like function mapping, filters and reducing. Ruby also supports an alternative syntax for the basic iterating method each, the following two examples are equivalent:

(0..42).each do |n| puts n end ...and... for n in 0..42 puts n end

Python


Iterators in Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
 are a fundamental part of the language and in many cases go unseen as they are implicitly used in the for (foreach
Foreach

For each is a computer language idiom for traversing items in a Collection class. Foreach is usually used in place of a standard for loop statement ....
) statement, in list comprehension
List comprehension

A list comprehension is a Syntax of programming languages construct available in some programming languages for creating a list based on existing lists....
s, and in generator expressions
Python syntax and semantics

The syntax of the Python is the set of rules that defines how a Python program will be written and interpreted . Python was designed to be a highly readable language....
. All of Python's standard built-in sequence types support iteration, as well as many classes which are part of the standard library. The following example shows typical implicit iteration over a sequence:

for value in sequence: print value

Python dictionaries (a form of associative array
Associative array

An associative array is an abstract data type composed of a Collection of unique keys and a collection of values, where each key is associated with one value ....
) can also be directly iterated over, when the dictionary keys are returned; or the items method of a dictionary can be iterated over where it yields corresponding key,value pairs as a tuple:

for key in dictionary: value = dictionary[key] print key, value

for key, value in dictionary.items: print key, value

Iterators however can be used and defined explicitly. For any iteratable sequence type or class, the builtin function iter is used to create an iterator object. The iterator object then provides a next method which returns the next element in the container. It will raise a StopIteration error when no more elements are left. The following example shows an equivalent iteration over a sequence using explicit iterators:

it = iter(sequence) while True: try: value = it.next except StopIteration: break print value

Any user-defined class can support standard iteration (either implicit or explicit) by defining an __iter__ method which creates an iterator object. The iterator object then needs to define a next method which returns the next element.

Python's generators
Iterator

In computer science, an iterator is an object that allows a programmer to traverse through all the elements of a Collection , regardless of its specific implementation....
 implement this iteration protocol.

PHP

PHP
PHP

PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
 4 introduced a foreach construct, much like Perl
Perl

In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
 and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays in PHP 4, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

In PHP 5, foreach is allowed on object iterating through all the public members.

There are two syntaxes; the second is a minor but useful extension of the first.

Example A Example B $value) echo "($key)$value\n"; ?>

The Example A loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The Example B has the same functionality as above. Additionally, the current element's key (in this case, array_expression) will be assigned to the variable $key on each loop.

The Iterator interface is pre-defined in PHP 5 and objects can be customized to handle iteration. These methods are all being used in a complete foreach($obj AS $key=>$value) sequence. The methods of Iterators are executed in the following order: 1. rewind 2. while valid

See also


  • Iteration
    Iteration

    Iteration means the act of repeating....
  • Iterator pattern
    Iterator pattern

    In object-oriented programming, the Iterator pattern is a Design pattern in which iterator are used to access the elements of an aggregate object sequentially without exposing its underlying representation....
  • Visitor pattern
    Visitor pattern

    In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure upon which it operates....
  • Design pattern
    Design pattern (computer science)

    In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code ....


External links

  • Article "" by Joshua Gatcomb
  • Article "" (217 KB) by Stephen M. Watt
  • -