# 迭代器

## 範例

### C♯

```// Method that takes an iterable input (possibly an array)
// and returns all even numbers.
public static IEnumerable<int> GetEven(IEnumerable<int> numbers)
{
foreach(int i in numbers)
{
if (i % 2 == 0) yield return i;
}
}
```

### C++

C++STL可支持迭代器。

```template<typename InputIterator>
void printall(InputIterator first, InputIterator last)
{
for(; first != last; ++first)
{
std::cout << *first << std::endl;
}
}
```

### Java

Java JDK 1.2 版開始支持迭代器。每一個迭代器提供`next()`以及`hasNext()`方法，同時也支持remove()。

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

### Python

```# 從序列得到
x = [42, "test", -12.34]
it = iter(x)
try:
while True:
x = next (it) # 在Python 2中，要改成it.next()
print(x)
except StopIteration:
pass

# generator
def foo(n):
for i in range(n):
yield i

it = foo(5)
try:
while True:
x = next(it) # 在Python 2中，要改成it.next()
print(x)
except StopIteration:
pass
```

### Ruby

Ruby程序員可以用yield關鍵字定義迭代器，又將迭代器和生成器分开。

```0..42.each do |n|
puts n
end
```

...以及...

```for n in 0..42
puts n
end
```

## 外部連結

• Iterators and generators. MDN Web Docs. [2018-10-16] （美国英语）.