In computer programming, an iterator is an object that progressively provides access to each item of a collection, in order.
A collection may provide multiple iterators via its interface that provide items in different orders, such as forwards and backwards.
An iterator is often implemented in terms of the structure underlying a collection implementation and is often tightly coupled to the collection to enable the operational semantics of the iterator.
An iterator is behaviorally similar to a database cursor.
Iterators date to the CLU programming language in 1974.
An iterator allows a consumer to process each element of a collection while isolating the consumer from the internal structure of the collection. The collection can store elements in any manner while the consumer can access them as a sequence.
In object-oriented programming, an iterator class is usually designed in tight coordination with the corresponding collection class. Usually, the collection provides the methods for creating iterators.
A loop counter is sometimes also referred to as a loop iterator. A loop counter, however, only provides the traversal functionality and not the element access functionality.
def fibonacci(limit: int) -> Generatorint,:
a, b = 0, 1
for _ in range(limit):
yield a
a, b = b, a + b
for number in fibonacci(100): # The generator constructs an iterator
print(number)
digits: listint = 0,
squared_digits: Iteratorint = map(lambda x: x ** 2, digits)
An implicit iterator is often manifest in language syntax as [[foreach]].
In Python, a collection object can be iterated directly:
print(value)
In Ruby, iteration requires accessing an iterator property:
puts value
end
This iteration style is sometimes called "internal iteration" because its code fully executes within the context of the iterable object (that controls all aspects of iteration), and the programmer only provides the operation to execute at each step (using an anonymous function).
Languages that support list comprehensions or similar constructs may also make use of implicit iterators during the construction of the result list, as in Python:
Sometimes the implicit hidden nature is only partial. The C++ language has a few function templates for implicit iteration, such as for_each(). These functions still require explicit iterator objects as their initial input, but the subsequent iteration does not expose an iterator object to the user.
The ability of a collection 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. This assertion must however be taken with a grain of salt, because more often than not, for efficiency reasons, the iterator implementation is so tightly bound to the collection that it does preclude modification of the underlying collection without invalidating itself.
For collections that may move around their data in memory, the only way to not invalidate the iterator is, for the collection, to somehow keep track of all the currently alive iterators and update them on the fly. Since the number of iterators at a given time may be arbitrarily large in comparison to the size of the tied collection, updating them all will drastically impair the complexity guarantee on the collection's operations.
An alternative way to keep the number of updates bound relatively to the collection size would be to use a kind of handle mechanism, that is a collection of indirect pointers to the collection's elements that must be updated with the collection, and let the iterators point to these handles instead of directly to the . But this approach will negatively impact the iterator performance, since it must effectuate a double pointer following to access the actual data element. This is usually not desirable, because many algorithms using the iterators invoke the iterators data access operation more often than the advance method. It is therefore especially important to have iterators with very efficient data access.
All in all, this is always a trade-off between security (iterators remain always valid) and efficiency. Most of the time, the added security is not worth the efficiency price to pay for it. Using an alternative collection (for example a singly linked list instead of a vector) would be a better choice (globally more efficient) if the stability of the iterators is needed.
| C++, Rust |
| C++ |
| C++ |
| C++ |
| C++ |
| C++ (old STL) |
| PHP, R |
| PHP |
| C++, PHP |
| PHP, Python |
| PHP, R |
| PHP |
| C#, Java, R |
| PHP |
| PHP |
Enumerators are typically obtained by calling the GetEnumerator() method of an object implementing the System.Collections.IEnumerable interface. a Current property, to obtain the value of the element currently being pointed at; Collection classes typically implement this interface. However, the foreach statement in C# can operate on any object providing such a method, even if it does not implement System.Collections.IEnumerable (duck typing). Both interfaces were expanded into generic versions in .NET 2.0.
The following shows a simple use of iterators in C# 2.0:
// explicit version
IEnumerator
// implicit version
foreach (Foo foo in list)
{
C# 2.0 also supports generators: a method that is declared as returning System.Collections.IEnumerator (or System.Collections.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.
The following demonstrates a linked list of
typedef struct {
LinkedListIterator list_begin(LinkedList* head) {
int* list_next(LinkedListIterator* it) {
int main() {
Traversal using iterators usually involves a single varying iterator, and two fixed iterators that serve to delimit a range to be traversed. The distance between the limiting iterators, in terms of the number of applications of the operator ++ needed to transform the lower limit into the upper one, equals the number of items in the designated range; the number of distinct iterator values involved is one more than that. By convention, the lower limiting iterator "points to" the first element in the range, while the upper limiting iterator does not point to any element in the range, but rather just beyond the end of the range.
For traversal of an entire container, the begin() method provides the lower limit, and end() the upper limit. The latter does not reference any element of the container at all but is a valid iterator value that can be compared against.
The following example shows a typical use of an iterator.
using std::vector;
int main() {
Iterator types are separate from the container types they are used with, though the two are often used in concert. The category of the iterator (and thus its defined operations) usually depends on the type of container, with for instance arrays or vectors providing random access iterators, but sets (which use a linked structure as implementation) only providing bidirectional iterators. One same container type can have more than one associated iterator type; for instance the std::vector<T> container type allows traversal either using (raw) pointers to its elements (of type T*), or values of a special type std::vector<T>::iterator, and yet another type is provided for "reverse iterators", whose operations are defined in such a way that an algorithm performing a usual (forward) traversal will actually do traversal in reverse order when called with reverse iterators. Most containers also provide a separate const_iterator type, for which operations that would allow changing the values pointed to are intentionally not defined.
Simple traversal of a container object or a range of its elements (including modification of those elements unless a const_iterator is used) can be done using iterators alone. But container types may also provide methods like insert() or erase() that modify the structure of the container itself; these are methods of the container class, but in addition require one or more iterator values to specify the desired operation. While it is possible to have multiple iterators pointing into the same container simultaneously, structure-modifying operations may invalidate certain iterator values (the standard specifies for each case whether this may be so); using an invalidated iterator is an error that will lead to undefined behavior, and such errors need not be signaled by the run time system.
Implicit iteration is also partially supported by C++ through the use of standard function templates, such as [https://en.cppreference.com/w/cpp/algorithm/for_each std::for_each()],
[https://en.cppreference.com/w/cpp/algorithm/copy std::copy()]
and
[https://en.cppreference.com/w/cpp/algorithm/accumulate std::accumulate()].
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().
// Function that will process each item of the collection.
void processItem(const Foo& i) {
// A for-each iteration loop.
std::for_each(c.begin(), c.end(), processItem);
// using std::ranges:
std::ranges::for_each(c, processItem);
The same can be achieved using std::copy, passing a [https://en.cppreference.com/w/cpp/iterator/ostream_iterator std::ostream_iterator] value as third iterator:
std::copy(c.begin(), c.end(), ostream_iterator
// A for-each iteration loop with a lambda function.
std::for_each(c.begin(), c.end(), (const Foo& i) -> void { std::println("{}", i); });
// Using std::ranges:
std::ranges::for_each(c, (const Foo& i) -> void { std::println("{}", i); });
The Java-style syntax for iterators (Iterator<T>, vs T::iterator) is achieved with the type std::ranges::iterator_t<T>.
using std::vector;
using std::ranges::iterator_t;
// can now be called like this:
int main() {
C++23 introduces generators to C++ with a std::generator<Ref, V, Alloc>, which are like iterators, but rely on , and yield an item through the
The next() method advances the iterator and returns the value pointed to by the iterator. The first element is obtained upon the first call to next(). To determine when all the elements in the collection have been visited the hasNext() test method is used. The following example shows a simple use of iterators:
Iterator
To show that hasNext() can be called repeatedly, we use it to insert commas between the elements but not after the last element.
This approach does not properly separate the advance operation from the actual data access. If the data element must be used more than once for each advance, it needs to be stored in a temporary variable. When an advance is needed without data access (i.e. to skip a given data element), the access is nonetheless performed, though the returned value is ignored in this case.
For collection types that support it, the remove() method of the iterator removes the most recently visited element from the collection while keeping the iterator usable. Adding or removing elements by calling the methods of the collection (also from the same thread) makes the iterator unusable. An attempt to get the next element throws the exception. An exception is also thrown if there are no more elements remaining (hasNext() has previously returned false).
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 5.0 release of Java introduced the interface to support an for-each (foreach) loop for iterating over collections and arrays. java.lang.Iterable defines the method that returns an java.util.Iterator<E>. Using the for-each loop, the preceding example can be rewritten as
Some collections also use the older (since 1.0) class. It provides hasMoreElements() and nextElement() methods but has no methods to modify the collection.
Java iterators and collections can be automatically converted into Scala iterators and collections, respectively, simply by adding the single line
for n = myArray
traverses an array of integers using the for keyword.
In the case of internal iteration where the user can supply an operation to the iterator to perform over every element of a collection, many built-in operators and MATLAB functions are overloaded to execute over every element of an array and return a corresponding output array implicitly. Furthermore, the arrayfun and cellfun functions can be leveraged for performing custom or user defined operations over "native" arrays and cell arrays respectively. For example,
% Perform a custom operation over each element
myNewArray = arrayfun(@(a)myCustomFun(a),myArray);
% Echo resulting array to Command Window
myNewArray
function outScalar = myCustomFun(inScalar)
% Simply multiply by 2
outScalar = 2*inScalar;
defines a primary function simpleFun that implicitly applies custom subfunction myCustomFun to each element of an array using built-in function arrayfun.
Alternatively, it may be desirable to abstract the mechanisms of the array storage container from the user by defining a custom object-oriented MATLAB implementation of the Iterator Pattern. Such an implementation supporting external iteration is demonstrated in MATLAB Central File Exchange item Design Pattern: Iterator (Behavioral). This is written in the new class-definition syntax introduced with MATLAB software version 7.6 (R2008a) and features a one-dimensional cell array realization of the List Abstract Data Type (ADT) as the mechanism for storing a heterogeneous (in data type) set of elements. It provides the functionality for explicit forward List traversal with the hasNext(), next() and reset() methods for use in a while-loop.
The simplest implementation is by wrapping an array, this can be useful for type hinting and information hiding.
final class ArrayIterator extends \Iterator
{
All methods of the example class are used during the execution of a complete foreach loop (foreach ($iterator as $key => $current) {}). The iterator's methods are executed in the following order:
The next example illustrates a PHP class that implements the Traversable interface, which could be wrapped in an IteratorIterator class to act upon the data before it is returned to the foreach loop. The usage together with the MYSQLI_USE_RESULT constant allows PHP scripts to iterate result sets with billions of rows with very little memory usage. These features are not exclusive to PHP nor to its MySQL class implementations (e.g. the PDOStatement class implements the Traversable interface as well).
// The \mysqli_result class that is returned by the method call implements the internal Traversable interface.
foreach ($mysqli->query('SELECT `a`, `b`, `c` FROM `table`', MYSQLI_USE_RESULT) as $row) {
Python dictionaries (a form of associative array) 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:
Iterators however can be used and defined explicitly. For any iterable sequence type or class, the built-in function iter() is used to create an iterator object. The iterator object can then be iterated with the next() function, which uses the __next__() method internally, which returns the next element in the container. (The previous statement applies to Python 3.x. In Python 2.x, the next() method is equivalent.) A StopIteration exception will be raised when no more elements are left. The following example shows an equivalent iteration over a sequence using explicit iterators:
sequence: listint = 1,
it: Iteratorint = iter(sequence)
while True:
Any user-defined class can support standard iteration (either implicit or explicit) by defining an __iter__() method that returns an iterator object. The iterator object then needs to define a __next__() method that returns the next element.
Python's generators implement this iteration protocol.
The following example shows typical implicit iteration over a collection of values:
Raku hashes can also be directly iterated over; this yields key-value Pair objects. The kv method can be invoked on the hash to iterate over the key and values; the keys method to iterate over the hash's keys; and the values method to iterate over the hash's values.
for %word-to-number.kv -> $key, $value {
for %word-to-number.keys -> $key {
Iterators however can be used and defined explicitly. For any iterable type, there are several methods that control different aspects of the iteration process. For example, the iterator method is supposed to return an Iterator object, and the pull-one method is supposed to produce and return the next value if possible, or return the sentinel value IterationEnd if no more values could be produced. The following example shows an equivalent iteration over a collection using explicit iterators:
loop {
All iterable types in Raku compose the Iterable role, Iterator role, or both. The Iterable is quite simple and only requires the iterator to be implemented by the composing class. The Iterator is more complex and provides a series of methods such as pull-one, which allows for a finer operation of iteration in several contexts such as adding or eliminating items, or skipping over them to access other items. Thus, any user-defined class can support standard iteration by composing these roles and implementing the iterator and/or pull-one methods.
The DNA class represents a DNA strand and implements the iterator by composing the Iterable role. The DNA strand is split into a group of trinucleotides when iterated over:
for DNA.new('GATTACATA') {
say DNA.new('GATTACATA').map(*.join).join('-');
The Repeater class composes both the Iterable and Iterator roles:
for Repeater.new("Hello", 3) {
...and...
or even shorter
Ruby can also iterate over fixed lists by using Enumerators and either calling their #next method or doing a for each on them, as above.
Specifically, the
All collections provided by the standard library implement the std::iter::IntoIterator trait (meaning they define the into_iter() method). Iterators themselves implement the std::iter::Iterator trait, which requires defining the next() method. Furthermore, any type implementing std::iter::Iterator is automatically provided an implementation for std::iter::IntoIterator that returns itself.
Iterators support various adapters (map(), filter(), skip(), take(), etc.) as methods provided automatically by the std::iter::Iterator trait.
Users can create custom iterators by creating a type implementing the std::iter::Iterator trait. Custom collections can implement the std::iter::IntoIterator trait and return an associated iterator type for their elements, enabling their use directly in
impl Fibonacci {
impl Iterator for Fibonacci {
fn main() {
Console.WriteLine(iter.Current);
}
Console.WriteLine(foo);
}
C
int* value;
struct LinkedList* next;
} LinkedList;
LinkedList* current;
} LinkedListIterator;
LinkedListIterator it = { head };
return it;
}
if (!it->current) {
return NULL;
}
int* value = &it->current->value;
it->current = it->current->next;
return value;
}
// ...
for (LinkedListIterator it = list_begin(head); ; ) {
int* val = list_next(&it);
if (!val) {
break;
}
printf("%d\n", *val);
}
}
C++
vector
// Iterate through 'items'.
// 'it' is of type vector
// Using foreach loops (added in C++11),
// the same can be done without using any explicit iterators:
for (int x : items) {
// Print value of each element 'x' of 'items'.
std::print("{}", x);
}
// Both of the for loops print "529".
}
std::println("{}", i);
}
vector
}
Java
System.out.print(iter.next());
if (iter.hasNext()) {
System.out.print(", ");
}
}
System.out.println(obj);
}
Scala
MATLAB
% ... do something with n
disp(n) % Echo integer to Command Window
end
PHP
private array $array;
public function __construct(array $array)
{
$this->array = $array;
}
public function rewind(): void
{
echo 'rewinding' , PHP_EOL;
reset($this->array);
}
public function current()
{
$value = current($this->array);
echo "current: {$value}", PHP_EOL;
return $value;
}
public function key()
{
$key = key($this->array);
echo "key: {$key}", PHP_EOL;
return $key;
}
public function next()
{
$value = next($this->array);
echo "next: {$value}", PHP_EOL;
return $value;
}
public function valid(): bool
{
$valid = $this->current() !== false;
echo 'valid: ', ($valid ? 'true' : 'false'), PHP_EOL;
return $valid;
}
}
// Act on the returned row, which is an associative array.
}
Python
print(value)
value = dictionary[key]
print(key, value)
print(key, value)
try:
value = it.next() # in Python 2.x
value = next(it) # in Python 3.x
except StopIteration:
break
print(value)
Raku
say $value
}
say $pair;
}
say "$key: $value"
}
say "$key => " ~ %word-to-number{$key};
}
my $value := $it.pull-one; # grab iteration's next value
last if $value =:= IterationEnd; # stop if we reached iteration's end
say $value;
}
has $.chain;
method new(Strand:D $chain) {
self.bless: :$chain
}
method iterator(DNA:D:){ $.chain.comb.rotor(3).iterator }
};
.say
}
has Any $.item is required;
has Int $.times is required;
has Int $!count = 1;
multi method new($item, $times) {
self.bless: :$item, :$times;
}
method iterator { self }
method pull-one(--> Mu){
if $!count <= $!times {
$!count += 1;
return $!item
}
else {
return IterationEnd
}
}
}
.say
}
Ruby
puts n
end
puts n
end
puts n
end
Rust
println!("{}", i);
}
// Prints the numbers 0 to 41
pub fn new() -> Self {
Self(0, 1)
}
}
type Item = u64;
fn next(&mut self) -> Option
Some(next)
}
}
let fib = Fibonacci::new();
for n in fib.skip(1).step_by(2).take(4) {
println!("{n}");
}
// Prints 1, 2, 5, and 13
}
See also
External links
|
|